Created
August 25, 2011 19:30
-
-
Save mpezzi/1171590 to your computer and use it in GitHub Desktop.
PHP Validate Postal Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Validate a postal code. | |
* | |
* @param $value | |
* A postal code as string. | |
* @param $country | |
* The country postal code format. | |
* @return | |
* TRUE or FALSE if it validates. | |
*/ | |
function valid_postal_code($value, $country = 'ca') { | |
$country_regex = array( | |
'uk' => '/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\\b\\z/i', | |
'ca' => '/\\A\\b[ABCEGHJKLMNPRSTVXY][0-9][A-Z][ ]?[0-9][A-Z][0-9]\\b\\z/i', | |
'it' => '/^[0-9]{5}$/i', | |
'de' => '/^[0-9]{5}$/i', | |
'be' => '/^[1-9]{1}[0-9]{3}$/i', | |
'us' => '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i', | |
'default' => '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i' // Same as US. | |
); | |
if ( isset($country_regex[$country]) ) { | |
return preg_match($country_regex[$country], $value); | |
} | |
return preg_match($country_regex['default'], $value); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment