Javascript UK Postcode Validation

javascript, postal-code, regex, validation

Solution

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

Problem

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?

Original source

Related problems