Canada RegExp

ZIP Code (Postal Code) validation - UK, US, Canada RegExp

 Example:

function postalCodeCheck(postalCode, country) {

     if (!postalCode) {

        return false;

    }

 

    postalCode = postalCode.toString().trim();

 

    var us = new RegExp("^\\d{5}(-{0,1}\\d{4})?$");

    var ca = new RegExp(/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i);

    var uk = /^[A-Z]{1,2}[0-9RCHNQ][0-9A-Z]?\s?[0-9][ABD-HJLNP-UW-Z]{2}$|^[A-Z]{2}-?[0-9]{4}$/;

    var other = new RegExp("^\\d+$");

 

    if (country == "US") {

        if (us.test(postalCode.toString())) {

            return true;

        }

    }

    else if (country == "CA") {

        if (ca.test(postalCode.toString())) {

            return true;

        }

    }

    else if (country == "UK") {

        if (uk.test(postalCode.toString())) {

            return true;

        }

    }

    else {

        if (other.test(postalCode.toString())) {

           return true

        }

    }

 

    return false;

}

 

//postalCodeCheck("SW1W 0NY", "UK"); //True

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

ZIP Code (Postal Code) validation - UK, US, Canada RegExp ZIP Code (Postal Code) validation - UK, US, Canada RegExp Reviewed by Anil Singh on 5:50 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^