Possible Duplicate:
UK Postcode Regex (Comprehensive)
I have the following code for validating postcodes in javascript:
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
return regex.test(postcode);
}
Tests:
CF47 0HW - Passes - Correct
CF47 OHW - Passes - Incorrect
I have done a ton of research but can't seem to find the definitive regex for this common validation requirement. Could someone point me in the right direction please?
Make your regex stricter by adding ^ and $. This should work:
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
return regex.test(postcode);
}
You want a 'definitive regex' - given all the permutations of the UK postcodes, it needs to be therefore 'unnecessarily large'. Here's one I've used in the past
"(GIR 0AA)|((([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][ABCDEFGHJKSTUW])|([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][ABEHMNPRVWXY])))) [0-9][ABDEFGHJLNPQRSTUWXYZ]{2})"
Notice I never just use A-Z, for instance, because in each part there are always certain letters excluded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With