0

HTML

<form action="#" id="MyForm" name="MyForm">
<p id="message"></p>
<table id="tblData">
    <tr>
        <td>
            <label for="A">
                A</label>
            <input id="A" name="A" type="text" value="" />
        </td>
    </tr>
    <tr>
        <td>
            <label for="ZipCode">
                Zip Code</label>
            <input id="ZipCode" name="ZipCode" type="text" value="" />
        </td>
    </tr>
    <tr>
        <td>
            <span id="submitButton" class="k-button">Next</span>
        </td>
    </tr>
</table>
</form>

JQuery

$(document).ready(function () {
    $('#submitButton').click(function () {
        $('#MyForm').submit();
    });
    $.validator.addMethod(
            'regex',
            function (value, element, regexp) {
                var re = new RegExp(regexp);
                return this.optional(element) || re.test(value);
            }, "");

            $('#MyForm').validate(
        {
            rules: {
                A:
                {
                    required: false,
                    range: [1, 9999999999]
                }
            },
            messages: {
                A: {
                    range: jQuery.validator.format("Please enter a value between {0} and {1}.")
                }
            }
            ,
            highlight: function (element) {
                $(element).closest('.MyForm').removeClass('success').addClass('error');
            }
        });
    $("#ZipCode").rules("add", { regex: "^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z]( )?\d[a-zA-Z]\d)$",
        messages: {
            regex: "Zip code must be a Valid US or CA Zip"
        }
    });
});

Question : There is some issue with Zip Code. It's always saying. Please enter valid Zip Code. But when i test the regex with s/w it is working fine there...

enter image description here

JSFiddle - Demo

4

2 回答 2

2

我做了一些改变,现在工作正常

<script type="text/javascript">
    $("#ZipCode").rules("add",
        { regex: /^(\d{5}-\d{4}|\d{5}|\d{9})$|^([a-zA-Z]\d[a-zA-Z]( )?\d[a-zA-Z]\d)$/,
        messages: {
            regex: "Zip code must be a Valid US or CA Zip"
        }
    });


    $.validator.addMethod(
        'regex',
        function (value, element, regexp) {
            return regexp.test(value);
    }, "");
</script>
于 2013-09-13T15:20:52.413 回答
0

在 Javascript 中,您必须转义所有 Javascript 本身不使用的转义字符。用正则表达式中的双反斜杠替换所有反斜杠,或者(如该答案中的 OP 所述)表示使用正斜杠作为边界字符的正则表达式,而不是将其列为 javascript 将尝试解释的字符串。正斜杠是显式书写的语法糖new Regexp("...");

于 2013-09-13T14:33:03.277 回答