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
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);
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.