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?

Link to comment
Share on other sites

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.

Edited by Zane
Link to comment
Share on other sites

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";

Edited by ManiacDan
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.