Reputation: 601
I've written the following for insertion into my Parsley extras file in order to allow UK postcode validation via parsley.js
//postcode
window.Parsley.addValidator('postcode', {
requirementType: 'string',
validateString: function(value, requirement) {
var postcode = value.match(/^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$/) || [];
return postcode.length >= requirement;
},
messages: {
en: 'The postcode entered is invalid.'
}
});
It seems to not accept a space in the middle of the postcode, which strikes me as odd as I feel users will always be trying to add this.
To clarify, the regex in the rule I've setup is directly from UK government advice on the issue.
Have I got an invalid function or is this regex working as expected ? If anyone else has parsley working with UK Postcodes I've appreciate any info as surprisingly this doesn't seem to be covered at all on the parsley github page or elsewhere on the internet.
Upvotes: 0
Views: 609
Reputation: 344
It looks like your regex is simply missing a space.
See below to compare:
You:
^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$
Gov:
^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
Looks like you also have a dash missing: A-Z
not AZ
.
Upvotes: 1