Skip to content

Instantly share code, notes, and snippets.

@jefferyrdavis
Last active January 21, 2020 08:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jefferyrdavis/5992282 to your computer and use it in GitHub Desktop.
Save jefferyrdavis/5992282 to your computer and use it in GitHub Desktop.
Snippit: PHP: Simple US Zip Code format validation
<?php
/* Validates if $zipCode is a 5 digit number in the 12345 format. Note that this simply checks to see if $zipCode is a 5 digit number, not necessarily a valid U.S. Zip Code.
*/
function validateZipCode($zipCode) {
if (preg_match('#[0-9]{5}#', $zipCode))
return true;
else
return false;
}
?>
Copy link

ghost commented May 8, 2018

private function isValidZipCode($zipCode) {
	return (preg_match('#[0-9]{5}#', $zipCode)) ? true : false;
}

@FranciscoG
Copy link

tweaked a bit and it finally worked for me and includes the optional zip+4 validation if a user decides to include that

function isValidZipCode($zipCode) {
    return (preg_match('/^[0-9]{5}(-[0-9]{4})?$/', $zipCode)) ? true : false;
}

check it out here (changed the return from bool to string in this demo): https://repl.it/repls/NativeCornyProject

@lgebremedhin
Copy link

what bout to add empty zipcode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment