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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^