Another update for this module. Better detection of one too many characters in postal codes and additional correction of 'fat-fingering' the dash.
Code:
<?php
#########################################
## ## Validate Zipcode ## ##
#########################################
## Version: 1.2.6 (3/2/2004)
## Last updated: 6/8/2004
if (!defined('XCART_SESSION_START')) { header("Location: ../"); die("Access Denied!"); }
function validate_zipcode($zipcode,$country='') {
$zipcode = trim($zipcode); // Prep by removing excess spaces.
switch ($country) {
case 'US': // Validate United States postal codes.
if (strlen($zipcode) > 5 && strlen($zipcode) <= 10) { // If not length 5, then check for valid format.
if (preg_match("/^([0-9]{5})([-=._\/\ ])?([0-9]{4})?(.)?/", $zipcode, $checkZip)) {
if (!empty($checkZip[3])) { // Is it a zip+4 code?
# Prevent char deletion by concatenation or overflow during next part of validation code. Instead, cause an error.
if (empty($checkZip[4])) { // This checks if the last digit will be cutoff from an empty $checkZip[2].
if (empty($checkZip[2]) || $checkZip[2] != '-')
$checkZip[2] = '-'; // Ensure that a dash is present in 9 digit zip code.
$zipcode = $checkZip[1].$checkZip[2].$checkZip[3];
} else // Cause an error because there are 10 digits, instead of 9 with a partitioning character.
$zipcode = '';
} else // Cause an error from incorrect length.
$zipcode = '';
} else // No valid zip code matched.
$zipcode = '';
} elseif (strlen($zipcode) < 5 || preg_match("/[[:alpha:]]/i",$zipcode)) // Check min length or presence of a letter.
$zipcode = '';
# If none of the above, do not modify zipcode. It is a valid 5 numeric digits.
break;
case 'CA': // Validate Canadian postal codes.
if (strlen($zipcode) >= 6 && strlen($zipcode) <= 7) { // Check for valid length.
if (preg_match("/^([A-z0-9]{3})([-._\/\ ])([A-z0-9]{3})(.)?/i", $zipcode, $checkZip)) {
if (empty($checkZip[4])) {
if ($checkZip[2] != ' ')
$checkZip[2] = ' '; // Ensure that a space is between the two code segments.
$zipcode = $checkZip[1].$checkZip[2].$checkZip[3];
} else // Cause an error because there are 7 digits, instead of 6 with a partitioning character.
$zipcode = '';
} else // Cause an error from incorrect length.
$zipcode = '';
} else // No valid zip code matched.
$zipcode = '';
if (!empty($zipcode))
$zipcode = strtoupper($zipcode); // Capitalize alphabetic characters for Canadian postal code.
break;
}
return $zipcode;
}
?>
Again, let me know if you have problems with this so that I can correct any bugs.