﻿function ValidatePostcode(field) {
    postcode = IsPostcode(field.value);
    if (postcode) {
        field.value = postcode;
    }else{
		alert('The postcode you have entered does not appear to be valid. Please check and try again..');
		field.focus();
		return false;
	}
}


function IsPostcode(postcode) {
    if (postcode == '') {
        return false;
    }
    //remove any whitespace and make sure we've got caps
    postcode = postcode.replace(/ /g, '').toUpperCase();
    if (postcode.length >= 5 && postcode.length <= 7) {
        var outcode;
        var incode;
        incode = postcode.substring(postcode.length - 3, postcode.length);
        outcode = postcode.substring(0, postcode.length - 3);
        //list of all valid outcodes as per ftp://ftp.royalmail.com/Downloads/public/cmwalk/doc/active/doc21800003/PAF_Digest_Dec_03.pdf
        var outCodeValid = /([A-Z]([0-9]|[0-9][0-9]|[A-Z][0-9]|[A-Z][A-Z][0-9][0-9]|[0-9][A-Z]|[A-Z][0-9][A-Z]))/.test(outcode);
        var inCodeValid = /[0-9][A-Z][A-Z]/.test(incode);
        if (outCodeValid && inCodeValid) {
            //we've got a valid outcode
            return outcode + " " + incode;   
        } else {
            return false;
        }
    } else {
        return false;
    }
}