Validating Proper Postal Codes!

This function validates proper postal code formats for the United States of America, Canada, & United Kingdom.

- $city is the country code variable.
- $zip is postal code variable.


First lets start by starting hehe. We're going to make it into a function, define the function variables, trim the entered zipcode with the PHP function trim, then we'll add a php switch.

CODE
<?php
function pcv($city$zipc){

         
$zipc trim($zipc);
     
    switch(
$city){
?>



Next we're going to check for each area. The US, CA, & UK using the ereg / regex functions.

CODE
<?php

              
case "us":
        if (
ereg("^[0-9]{5}$",$zipc) || ereg("(^[0-9]{5})-([0-9]{4}$)",$zipc) || ereg("(^[0-9]{5}) ([0-9]{4}$)",$zipc)){ 
            return 
false;
        } else { 
            return 
true;
        }
     
                case 
"ca":
            if (
ereg("^[a-zA-Z][0-9][a-zA-Z][[:space:]][0-9][a-zA-Z][0-9]$",$zipc)){
            return 
false;
        } else { 
            return 
true;
        }
          
            case 
"uk":
            if (
ereg("^[a-zA-Z]{2}[0-9]{1,2} [0-9][a-zA-Z]{2}+$",$zipc)){ 
            return 
false;
        } else { 
            return 
true;
        }
        
            default:
            if (
ereg("^[a-zA-Z0-9]+[a-zA-Z0-9- ]+[a-zA-Z0-9]$",$zipc) && (strlen($zipc) < 15)){
            return 
false;
        } else { 
            return 
true;
        }

?>


Basically what this code above does is check for certain characters, such as numerials and letters. It detects where each number/letter is and put's it into each category. (US, CA, UK).


Here is an example of use:

CODE
<?php
if(pcv($city$zipc){ 
    echo 
"Error message, incorrect code";
        } else { 
    echo 
"Correct message, good code";
}
?>




And here is our full code.

CODE
<?php

function pcv($city$zipc){

         
$zipc trim($zipc);
     
    switch(
$city){

                case 
"us":
        if (
ereg("^[0-9]{5}$",$zipc) || ereg("(^[0-9]{5})-([0-9]{4}$)",$zipc) || ereg("(^[0-9]{5}) ([0-9]{4}$)",$zipc)){ 
            return 
false;
        } else { 
            return 
true;
        }
     
                case 
"ca":
            if (
ereg("^[a-zA-Z][0-9][a-zA-Z][[:space:]][0-9][a-zA-Z][0-9]$",$zipc)){
            return 
false;
        } else { 
            return 
true;
        }
          
            case 
"uk":
            if (
ereg("^[a-zA-Z]{2}[0-9]{1,2} [0-9][a-zA-Z]{2}+$",$zipc)){ 
            return 
false;
        } else { 
            return 
true;
        }
        
            default:
            if (
ereg("^[a-zA-Z0-9]+[a-zA-Z0-9- ]+[a-zA-Z0-9]$",$zipc) && (strlen($zipc) < 15)){
            return 
false;
        } else { 
            return 
true;
        }
          
    }       
?>

Saturday September 22, 2007 - 697 reads