﻿// Postcode validation - 2 methods can check full postcode, for registration etc, or just the outcode e.g. local search

function fnCheckPostCode() {
    var c = document.getElementById(pre + 'cboCounty').value;
    var p = document.getElementById(pre + 'tbxOutCode').value;
    if ((p.toUpperCase() != "OR ENTER POSTCODE.." || p != "") && c <= 0)
    {
        return formatPostcode(p)
    }
    return true;
}

//Runs postcode through regex functions below and returns formatted postcode with space
function formatPostcode(p) {
    if (isValidPostcode(p)) {
        var postcodeRegEx = /(^[A-Z]{1,2}[0-9]{1,2})([0-9][A-Z]{2}$)/i;
        var formattedPostcode = p.replace(postcodeRegEx, "$1 $2");
        document.getElementById(pre + 'tbxOutCode').value = formattedPostcode.toUpperCase();
        return true;
    }
    else {
        return false;
    }
}

/* tests to see if start of string matches BT1 - BT99  */
function isValidOutCode(p) {
    var postcodeRegEx = /bt[0-9]{1,2}/i;
    var errormessage = "The first part of the postcode must be between BT1 and BT99";
    if (!postcodeRegEx.test(p)) {
        alert(errormessage);
        return false;
    }
    return true;
}

/* tests to see if string is in correct UK style postcode: AL1 1AB, BM1 5YZ etc. */
function isValidPostcode(p) {
    var postcodeRegEx = /bt[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
    var errormessage = "Invalid postcode.  Please enter a full NI postcode, e.g. BT1 1AA";
    if (!postcodeRegEx.test(p)) {

        if (!isValidOutCode(p)) {
            return false;
        }
    }
    return true;
}