Skip to content

Instantly share code, notes, and snippets.

@mpezzi
Created August 25, 2011 19:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mpezzi/1171590 to your computer and use it in GitHub Desktop.
Save mpezzi/1171590 to your computer and use it in GitHub Desktop.
PHP Validate Postal Code
<?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