Jump to content

Validation A Phone Number When Submitting A Form


webguync

Recommended Posts

I am trying to validate a phone number when submitting a form. The code I am using to validate is

 


/* Phone Number Validation */
if(!mb_eregi("/[0-9]/","-",$phone))
$this->setError('phone', 'invalid phone number');
elseif(mb_strlen(trim($phone)) > 12)
$this->setError('phone', 'too long! 12 characters');

 

I want the format to be 123-123-1234

 

I get an invalid phone number display when I test and enter the phone number in that format. I must have something wrong. The phone name is set right and the variable $phone is right. Anything else to check?

Unless you are still using PHP4, there is no need to use the POSIX regular expression engine. ..aka ereg. You are much better off using PCRE aka... preg to validate. I especially do not understand the use of the multibyte function mainly because I have never used it myself... and I have been able to validate phone numbers just fine without it

 

Something like this should work just fine for a phone number

if(preg_match("#[0-9{3}-[0-9]{3}-[0-9]{4}#", $phoneNumber)) echo "valid phone number"

 

Although it isnt the most common and popular way of doing, it should get you on the right track.

You should probably anchor your exp<b></b>ression (and end statements with a semicolon), but otherwise Zane is right:

 

if(preg_match("#^[0-9]{3}-[0-9]{3}-[0-9]{4}$#", $phoneNumber)) echo "valid phone 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.