PHP- Postcode validation function
The PHP function below checks to see if a string is a valid UK postcode. If the string is valid, the function will return true.
//UK postcode validation check
function isPostcodeValid($postcode)
{
//remove all whitespace
$postcode = preg_replace('/\s/', '', $postcode);
//make uppercase
$postcode = strtoupper($postcode);
if(preg_match("/^[A-Z]{1,2}[0-9]{2,3}[A-Z]{2}$/",$postcode)
|| preg_match("/^[A-Z]{1,2}[0-9]{1}[A-Z]{1}[0-9]{1}[A-Z]{2}$/",$postcode)
|| preg_match("/^GIR0[A-Z]{2}$/",$postcode))
{
return true;
}
else
{
return false;
}
}
If you have any suggestions to improve the code, please contact me and share your version.