Canada’s postal code validation in PHP

Advertisement

Few days back, My friend Narendra asked me how to validate the postal code of Canada which is entered through the text box.And, I came up with this Php function as solution for him.

 

These are the conditions for validation of the postal code of Canada.

  1. There are six alphanumeric letters.
  2. Alphabate and digits are alternate and first letter must be alphabate.
  3. The alphabate shouldn’t contain letters “d”,”f”,”i”,”o”,”q” and “u”.

Postal code “A1B2c5” is a valid postal code whereas “A1f2cZ” or “1AC2E5” are invalid postal code of Canada.

//function to validate postal code of canada
function validateCanadaZip($zip_code)
{
 //function by Roshan Bhattara(http://roshanbh.com.np)
 if(preg_match("/^([a-ceghj-npr-tv-z]){1}[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}$/i",$zip_code))
    return true;
 else
    return false;
}

Now, let’s look at the explanation of the regular expression inside the preg_match() to validate the postal code of Canada as specified by the above condition. As you might know that a Perl compatible regular expression enclosed within “/” sign. The “i” at the end of the expression refers that this comparison is case insensitive.As most of you know, “^”sign is the start of the regular expression and “$” represent the end of the regular expression. And there are three repeated expressions like “([a-ceghj-npr-tv-z]){1}[0-9]{1}”. Let me explain it, the expression “([a-ceghj-npr-tv-z]){1}” represents that there should be one alphabate which doesn’t contain “d”,”f”,”i”,”o”,”q” and “i”. Furthermore, the expression “[0-9]{1}” represents that there should be one digit.

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

17 Comments on “Canada’s postal code validation in PHP”

  • Matt wrote on 26 March, 2008, 6:33

    I’m confused: “Postal code “A1B2cZ” is a valid postal code” …

    “Z” != [0-9]{1}

    furthermore, that’s not “alternating”…. the “Z” should be numeric per the rule #2, no?? “cZ” does not alternate between numeric/alpha… Just a point of curiosity more than anything.

  • Roshan wrote on 26 March, 2008, 6:54

    sorry for the confustion..that was mistakenly typed and corrected…..thanks a lott

  • rakesh wrote on 18 June, 2008, 10:55

    I am using PHP and Mysql(database ) I want to send bulk mail but my server not support .. my server guy told send bulk mail using your localhost … can any one help me.how can i send bulk mail ….. ?????

  • Mr. Gift Baskets wrote on 8 August, 2008, 13:45

    Hi Roshan, thank you for the great piece of code. One minor issue, the code requires 6 continuous characters, but many people put a space in the middle to make it A2A 2A2 instead of A2A2A2. Some international visitors might also do A2A2 A2 if that’s the format of their own country’s postal code. How can I allow for any spaces between characters?

    The Gift Basket King :) (a.k.a James)

  • pixelxdesign wrote on 11 September, 2008, 2:23

    @Mr. Gift Baskets

    You can just add str_replace in the function…

    <?

    /**
    * validateCanadaZip()
    *
    * function to validate postal code of canada
    * @source http://roshanbh.com.np/2008/03/canda-postal-code-validation-php.html
    * {@modified by} Fred-Eric Lafaille, http://www.pixelxdesign.com/
    *
    *
    *
    * @param mixed $zip_code
    * @return array ()
    */
    function validateCanadaZip($zip_code)
    {
    $zip_code = strtoupper($zip_code);
    $zip_code = str_replace(” “, “”, $zip_code);
    $zip_code = str_replace(“-“, “”, $zip_code);

    $count = count( $zip_code);

    if(strlen($zip_code) 6) {
    return array(false, $zip_code. ” 0x0001″);
    }

    //function by Roshan Bhattara(http://roshanbh.com.np)
    if(preg_match(“/^([a-ceghj-npr-tv-z]){1}[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}[a-ceghj-npr-tv-z]{1}[0-9]{1}$/i”,$zip_code))
    return array(true, $zip_code);
    else
    return array(false, $zip_code);
    }

    $zipcode = “h7w 5c6″;
    $result = validateCanadaZip($zipcode);
    if ($result['0']) {
    print $result['1'] .” est valide”;
    } else {
    print $result['1'] .” est non-valide”;
    }

    ?>

  • seetha wrote on 30 October, 2008, 9:32

    I am using PHP and Mysql(database ) I want to send bulk mail but my server not support .. my server guy told send bulk mail using your localhost … can any one help me.how can i send bulk mail ….. ?????

    i am using php and mysql i want to send bulk but server not support ..my server guy told send bulk mail using your localhost can.. any one help me how can i send bulk mail..?????

  • Fred wrote on 13 April, 2009, 22:49

    I used the function to validate postal code of canada to check postal code format
    But I find it too restrictive
    Lots of people use upper case o for Zero and vice versa
    also 1 and I (upper case i) are interchangeable
    Sure it’s not the correct format, but good enough for mailouts.

    can you post a modified function to allow for above?

  • Alex G wrote on 17 April, 2009, 16:04

    LOL @ Rakesh… hopefully it somehow involves a high speed collision between you and speeding train…

  • mike wrote on 16 May, 2009, 16:57

    there are only 18 valid letters for the first character of a postal code and Z is not one of them!

  • aou wrote on 4 August, 2009, 1:40

    Have you tried to use Yahoo or Google’s APIs to validate postal code? I’s as simple as sending http request to [google/yahoo] and validating the response.

  • tresloukadu wrote on 15 October, 2009, 13:52

    hello, do you know where i can find the adress information of canada? Im developing a system in php with ajax and when de user choses the province all cities are loaded and when a city is loaded all streets are loaded….. Do you know where i can find this database?

    thanks

  • Doug H wrote on 26 January, 2010, 22:34

    Why restrict your audience to just Canada? Why not the world. Check out http://intlmailaddress.com for a database of postal code formats in all countries in the world.

  • Riadh wrote on 29 January, 2010, 0:14

    @see http://www.canadapost.ca/tools/pg/manual/PGaddress-e.asp

    As my postal code was not considered to be a valid one, i reviewed your regex and the canada post website and found that only the first char has to represent one of the 18 regions.

    I also optimized it to proceed faster.

    preg_match(‘/^[abceghjklmnprstvxy][0-9][a-z][0-9][a-z][0-9]$/i’, $zip);

    @pixelxdesign : there is no need to use strtoupper as the modifier i(caseless) is in the regular expression. And in this case this modifier is fater than the strto(upper|lower) function.

  • Riadh wrote on 29 January, 2010, 0:24

    In new found land they have some postal code with (w|z) in the local delivery unit part (the second part).

    for example:

    A0A 3W0 is a valid postal code.
    A0A 3W0 | SOUTH RIVER | NEWFOUNDLAND AND LABRADOR | NL | 709 | Y | 47.535964 | -53.209132
    A0A 1Z0 is a valid postal code.
    A0A 1Z0 | CONCEPTION HARBOUR | NEWFOUNDLAND AND LABRADOR | NL | 709 | Y | 47.427521 | -53.225612

  • Riadh wrote on 29 January, 2010, 15:03

    @see http://en.wikipedia.org/wiki/Postal_codes_in_Canada
    @see http://en.wikipedia.org/wiki/List_of_postal_codes_in_Canada

    well now it’s my last comment! There is my final regular expression.

    No postal code includes the letters D, F, I, O, Q, or U, as the OCR equipment used in automated sorting could easily confuse them with other letters and digits[citation needed], especially when they are rendered as cursive handwriting. The letters W and Z are used, but are not currently used as the first letter.

    preg_match(‘/^[^dfioquwz][0-9][^dfioqu][0-9][^dfioqu][0-9]$/i’, $zipCode)

Trackbacks

  1. PHP Coding School » Blog Archive » php code [2008-03-24 16:59:21]
  2. KranF.com - Le Blogue » Archive du blogue » Valider un code postal Canadien en PHP

Write a Comment

 


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.