Javascript UK Postcode Validation

dai.hop picture dai.hop · Dec 20, 2012 · Viewed 32.8k times · Source

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?

Answer

paulgrav picture paulgrav · Dec 20, 2012

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);
}