Reputation: 769
I mask the phone numbers like "(342) 004-1452" with jQuery. Now I am trying validate this input with PHP. I tried
if(!preg_match('\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}', $_POST['tel']))
{
$errors['tel']='enter a valid phone number';
}
But I think my preg_match expression is not valid. What is the right preg_match expression to validate this data?
Upvotes: 1
Views: 912
Reputation: 32232
You're all over-thinking it. All you truly need to do is verify that the given string contains the proper number of numeric characters.
$input = '(342) 004-1452';
$stripped = preg_replace('/[^0-9]/', '', $input);
if( strlen($stripped) != 10 ) {
printf('%s is not a valid phone number.', $input);
} else {
printf('%s is a valid phone number. yay.', $input);
}
//output: (342) 004-1452 is a valid phone number. yay.
You can pretty-fy the phone number back from whatever garbled input someone has fed it with:
$phone_pretty = sprintf('(%s) %s-%s',
substr($stripped,0,3),
substr($stripped,3,3),
substr($stripped,6,4)
);
Upvotes: 2
Reputation: 168655
Your expression looks okay, but preg_match()
needs you to supply delimiters for the start and end of the regular expression within the quotes.
These markers are typically slashes, but can actually be a number of other characters.
So adding slashes to your line of code gives the following:
if(!preg_match('/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/', $_POST['tel']))
If you want the string to be only a phone number and nothing else, you may also want to limit the regex by adding ^
at the beginning and $
at the end:
if(!preg_match('/^\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}$/', $_POST['tel']))
Hope that helps.
(that said, I would add that the phone number format you're checking only applies for US and countries in the US dialling plan; most international countries use different formats, so if you want to accept international visitors, you'll need a much looser regex than this)
Upvotes: 1
Reputation: 239240
Your regular expression is missing delimiters. Wrap it with /
:
'/\(?[2-9][0-8][0-9]\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}/'
If you've configured your environment to display warnings, you should be seeing one:
PHP Warning: preg_match(): Delimiter must not be alphanumeric or backslash
If you haven't turned on warnings, or have intentionally turned them off, you should stop developing PHP code until you turn them back on.
Upvotes: 1