简体   繁体   中英

Jquery Postal code clientvalidate

I am working on a customvalidator to validate and replace (if possible) a postal code. This is a Dutch postal code and should look like "5050 AA". When the user enters "5050AA" this postal code should be replaced with "5050 AA". I tried this by adding the following script to my page, which is called in the customvalidator:

 <script type="text/javascript">
            function Postcode_ClientValidate(source, arguments) {
                var val = arguments.Value
                var result = "";
                var myPCRegExp1 = new RegExp("^[1-9][0-9]{3}\s?[a-zA-Z]{2}$", "i");
                var myPCRegExp2 = new RegExp("(\d{4}) (\w{2})");    

                if ((!myPCRegExp1.test(val)) && (!myPCRegExp2.test(val))) {
                    arguments.IsValid = false;
                } else {
                    if (myPCRegExp1.test(val)) {
                        arguments.Value = val.replace(myPCRegExp1, "$1, $2");
                        arguments.IsValid = true;
                    } else if (myPCRegExp1.test(val)) {
                        arguments.IsValid = true;
                    }               
                }

                //jQuery("input#[HIERDEID]").val("Test");
            }
        </script>

However, the script above is picking up the "5038AA" but not the "5038 AA" as a match, so i can't validate a working postal code and can't rewrite to the valid postal code. What am I doing wrong?

It's a standard .aspx page with a form and a customvalidator:

Try battling it out with this tool:

http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx for testing this sort of thing.

"5038 AA" is matching myPCRegExp1, too, because of the '\\s?'

I think you need this:

var myPCRegExp1 = new RegExp("^([1-9][0-9]{3})([a-zA-Z]{2})$", "i");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM