Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript UK Postcode Validation [duplicate]

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?

like image 520
dai.hop Avatar asked Dec 20 '12 09:12

dai.hop


2 Answers

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);
}
like image 120
paulgrav Avatar answered Sep 28 '22 18:09

paulgrav


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.

like image 41
duncan Avatar answered Sep 28 '22 18:09

duncan