Jump to content

How to Valid Phone Numbers when NO Spaces between Digits


n1concepts

Recommended Posts

Can someone advise the edit required to include validation of US phone numbers ($phone_number3) when entered with no spaces between the area code and/or prefix.

 

Note: I have working code (regular expression) that validates phone numbers that enclose the area code with parenthesis or having a space, hyphen, or dot between area code, prefix, or last four digits.

 

Examples:  all three shown below are validated based on regular expresion

(123) 456-7890

123.456.7890

123 456 7890

 

However, I want to also include the option for 1234567890 (phone number have NO spaces) as valid.

 

I know the edit will be within ( |-|.)  using the PIPE but not sure how to denote the "no space" syntax within the regular expression.

 

See the regular expression: $good_phone = "^\(?[0-9]{3}\)?( |-|.)[0-9]{3}(-|.)[0-9]{4}$";

 

and if you wan to view the entire php snippet

 

// function which validates an American phone number

function validate_phone($phone_number) {
   $good_phone = "^\(?[0-9]{3}\)?( |-|.)[0-9]{3}(-|.)[0-9]{4}$";

   if (preg_match("/$good_phone/", $phone_number)) {
  echo "$phone_number is valid.<br/>";
   }
   else echo "$phone_number is NOT valid.<br/>";
}

$phone_number1 = "123.456.7890";
validate_phone($phone_number1);

$phone_number2 = "(123) 456-7890";
validate_phone($phone_number2);

$phone_number3 ="1234567890";
validate_phone($phone_number3);

 

You are making it harder than it needs to be. Simply use regex to remove all non-numeric characters and then determine if there are exactly 10 digits. You can then format the phone number as you wish in a consistent format.

function validPhone($phone)
{
    $phone = preg_replace("#[^\d]#", '', $phone);
    if(strlen($phone) != 10) { return false; }
    return '('.substr($phone, 0, 3).') '.substr($phone, 3, 3).'-'.substr($phone, 6);
}

validPhone('1234567890')     //Output: (123) 456-7890
validPhone('123-456-7890')   //Output: (123) 456-7890
validPhone('123.456.7890')   //Output: (123) 456-7890
validPhone('(123) 456-7890') //Output: (123) 456-7890
validPhone('123456789')      //Output: false
validPhone('123-4567')       //Output: false

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.