Jump to content

Phone Number validation help


coupe-r

Recommended Posts

Hi All,

 

I only want to allow phone number in ###-###-####.  Anything else I want an error.  Here is what I have, which says any number is valid.

 

Function:

function checkPhone($number)
{
if(preg_match('^[0-9]{3}+-[0-9]{3}+-[0-9]{4}^', $number))
{
	return $number;
}
	else
	{
               $items = Array('/\ /', '/\+/', '/\-/', '/\./', '/\,/', '/\(/', '/\)/', '/[a-zA-Z]/');
    	               $clean = preg_replace($items, '', $number);
        	       return substr($clean, 0, 3).'-'.substr($clean, 3, 3).'-'.substr($clean, 6, 4);
	}
}

 

 

Checking Number:

$number = '1231231234';

if(checkPhone($number))
{
echo $number.' is a valid phone number.';
}
else
{
	echo $number.' is not a valid phone number.';
}

 

This should give me the not valid message.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/226530-phone-number-validation-help/
Share on other sites

That logic is a little backwards. You are trying to list all the characters to replace. It's easier to define the regex expression to replace all characters except numbers. Then you still need to check if there are the right number of digits.

 

I think this will work better for you

function checkPhone($number)
{
    //Remove all non digit characters
    $number = preg_replace("#[^\d]#", '', $number);
    //If less than 10 digits return false
    if(strlen($number)<10) { return false; }
    //Return formatted number
    return preg_replace("#(\d{3})(\d{3})(\d{4})#", "$1-$2-$3", $number);
}

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.