问题
I have built a script to lookup flood areas via postcode and I'm looking to validate the field, I currently have a custom jQuery Validate method as the following.
jQuery.validator.addMethod("postcodeUK", function (value, element) {
return this.optional(element) || /[A-z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i.test(value);
}, "Please specify a valid Postcode");
The only issue is I require the space in-between for example AB12 3CD or BC1 9GH. It current allows AB123CD or BC19GH.
回答1:
You've made the space optional by following it with ?. If you want to require it, remove that ?.
A couple of other notes:
[A-z]is not just A-Z and a-z but also[,\,],_, and backtick (the characters betweenZanda). Since you're using theiflag, you want[A-Z]or[a-z]there.You probably want
^at the beginnning and$at the end to match against the whole input, not just a subset.
Example on regex101.com (you don't need the g or m flags I used there, that was just so I could show multiple examples in the testing area)
回答2:
There is already a proven method for validating UK Postcodes contained within the additional-methods.js file of the jQuery Validate plugin. Include this file or simply copy the method into your code, and then use the postcodeUK rule.
// Matches UK postcode. Does not match to UK Channel Islands that have their own postcodes (non standard UK)
$.validator.addMethod( "postcodeUK", function( value, element ) {
return this.optional( element ) || /^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))\s?([0-9][ABD-HJLNP-UW-Z]{2})|(GIR)\s?(0AA))$/i.test( value );
}, "Please specify a valid UK postcode" );
来源:https://stackoverflow.com/questions/36015372/jquery-validate-uk-postcode