Validate Canadian Postal Code


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function fnValidatePostal($mValue, $sRegion = '')
  2. {
  3. $mValue = strtolower($mValue));
  4. $sFirst = substr($mValue, 0, 1);
  5. $sRegion = strtolower($sRegion);
  6.  
  7. $aRegion = array(
  8. 'nl' => 'a',
  9. 'ns' => 'b',
  10. 'pe' => 'c',
  11. 'nb' => 'e',
  12. 'qc' => array('g', 'h', 'j'),
  13. 'on' => array('k', 'l', 'm', 'n', 'p'),
  14. 'mb' => 'r',
  15. 'sk' => 's',
  16. 'ab' => 't',
  17. 'bc' => 'v',
  18. 'nt' => 'x',
  19. 'nu' => 'x',
  20. 'yt' => 'y'
  21. );
  22.  
  23. if (preg_match('/[abceghjlkmnprstvxy]/', $sFirst) && !preg_match('/[dfioqu]/', $mValue) && preg_match('/^\w\d\w[- ]?\d\w\d$/', $mValue))
  24. {
  25. if (!empty($sRegion) && array_key_exists($sRegion, $aRegion))
  26. {
  27. if (is_array($aRegion[$sRegion]) && in_array($sFirst, $aRegion[$sRegion]))
  28. {
  29. return true;
  30. }
  31. else if (is_string($aRegion[$sRegion]) && $sFirst == $aRegion[$sRegion])
  32. {
  33. return true;
  34. }
  35. }
  36. else if (empty($sRegion))
  37. {
  38. return true;
  39. }
  40. }
  41.  
  42. return false;
  43. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.