jQuery Validate UK Postcode

徘徊边缘 提交于 2019-12-24 13:30:48

问题


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 between Z and a). Since you're using the i flag, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!