webguync Posted October 23, 2012 Share Posted October 23, 2012 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? Quote Link to comment https://forums.phpfreaks.com/topic/269826-validation-a-phone-number-when-submitting-a-form/ Share on other sites More sharing options...
Zane Posted October 23, 2012 Share Posted October 23, 2012 (edited) 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 October 23, 2012 by Zane Quote Link to comment https://forums.phpfreaks.com/topic/269826-validation-a-phone-number-when-submitting-a-form/#findComment-1387255 Share on other sites More sharing options...
ManiacDan Posted October 23, 2012 Share Posted October 23, 2012 (edited) 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 October 23, 2012 by ManiacDan Quote Link to comment https://forums.phpfreaks.com/topic/269826-validation-a-phone-number-when-submitting-a-form/#findComment-1387261 Share on other sites More sharing options...
Christian F. Posted October 23, 2012 Share Posted October 23, 2012 Add a closing square bracket before the first quantifier, and we're all in agreement. Quote Link to comment https://forums.phpfreaks.com/topic/269826-validation-a-phone-number-when-submitting-a-form/#findComment-1387265 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.