简体   繁体   中英

Validate Phone Number and Zip Code PHP

I am trying to validate a phone number and require it to have 10 digits only no spaces or special characters allowed (example: 0123456789) and the same goes with zip code except 5 digits only (example: 01234).

This is what I have for the phone number field so far.

$phone = stripslashes($_POST['phone']);

if(!$phone || $phone == "Phone Number*")
{
$error .= "Please enter your phone number.<br />";
}

The next if statement should retrieve an error similar to "Please enter a valid phone number. Example: "0123456789".

If you don't want to use regular expressions , take a look at ctype_digit

For example:

if(strlen($phone)==10 && ctype_digit($phone)) {
    //valid
} else {
    //invalid
}

I can't testify to whether this will be faster or slower than regular expressions, but I would reckon it's probably moot. It's more or less what makes the most sense to you.

You can try regex here:

if(preg_match('/^[0-9]{10}$/', $phone)){
    // valid
}else{
    // Not valid
}

Something a little like that will ensure only numerical characters and 10 of them. Just change the 10 to 5 for zip code.

One more thing if $_POST['phone'] is not set when you access it you will get a E_NOTICE so just a tip here for you do:

$phone = isset($_POST['phone']) ? stripslashes($_POST['phone']) : null;

if(!$phone) // ERROR
$phone = stripslashes($_POST['phone']);

if(!$phone || $phone == "Phone Number*")
{
$error .= "Please enter your phone number.<br />";
}

if(!preg_match('/^\d{10}$/', $phone)) $error .= "Please enter phone number as ##########.<br />";

And for zip code

if(!preg_match('/^\d{5}$/', $zip)) $error .= "Please enter your zip code as #####.<br />";

Keep in mind that this will not allow foreign zip codes (which may be of different lengths or include letters)


Just some other suggestions too (to prevent unnecessary error messages)

You may want to process your user input such that 123-456-7890 becomes 1234567890 by doing something like

preg_replace('/[^\\d]/','',$input)

Maybe do a trim($input) to strip leading/trailing whitespace


Finally, is there any particular reason you are using stripslashes on $_POST['phone']? If they are all digits like you expect, then this shouldnt be necessary. If they aren't all digits, then you will throw an error regardless

how about:

function check($number,$length)
{
  if(ctype_digit ($number) && strlen($number)==$length)
    return true;
  else
    return false;
}


if(check("1234",4))
  echo "ok";
else
  echo "Please enter a valid phone number. Example: "0123456789";

Well, this an old post but I will throw in some comments here anyway.

1) you should really not force the user to put in the right numbers, of course your validation on the front end will cover this but never assume it to be case coming into the "backend" .

Consider the following instead of putting the on the user:

// remove chars
$number = preg_replace('/[\D]/', '', $number);

//unit test sanitizer
filter_var($number, FILTER_SANITIZE_NUMBER_INT)

// check number
preg_match('/^[0-9]{10}$/', $zip)

Example : Read in user input if enough digits entered in look up closest matching zipcode etc.. (I actually used this on a site once) Of course setting the frontend to check is useful, but in case that fails .

$number = 'z 02012s';

// remove chars
$number = preg_replace('/[\D]/', '', $number);

//unit test sanitizer
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);

// check number
if (preg_match('#^[0-9]{5}$#', $number) === 1) {
    //(optional) lookup closest zip using your DB.
    $look_zip = $db->getClosestZipMatch($number);
} else {
    echo $number . " isn't 5 digits only, do something.";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM