Pankaj
Pankaj

Reputation: 10095

regex not working for ZipCode

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

Upvotes: 0

Views: 153

Answers (2)

abiessu
abiessu

Reputation: 1927

Within Javascript, you must escape all escape characters that are not used by the Javascript itself. Replace all backslashes with double backslashes within your regex, or (as noted by OP in that answer), denote a regex using forward slashes as boundary characters instead of listing it as a string that javascript will attempt to interpret. Forward slashes are syntactic sugar for explicitly writing new Regexp("...");.

Upvotes: 0

Pankaj
Pankaj

Reputation: 10095

I did few changes and working fine now

<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>

Upvotes: 2

Related Questions