i have this function to check my phone number:
function isValid( $what, $data ) {
switch( $what ) {
// validate a phone number
case 'phone_number':
$pattern = "/^[0-9-+]+$/";
break;
default:
return false;
break;
}
return preg_match($pattern, $data) ? true : false;
}
i want to change that regex to accept the following: the )
(
chars like (800) and the space
.
So for example this number will pass the validation, right now is not passing:
+1 (201) 223-3213
Let us construct the regular expression step by step. Consider also that spaces are trimmed before matching.
\+?
[0-9]+
You might want to write [0-9]*
if the number can begin directly with a group in parenthesis(\[0-9]+\)?
. Suppose that only one such group is allowed[0-9-]*
the final character must be a digit [0-9]
, hyphen is not allowed here
^\+?[0-9]+(\([0-9]+\))?[0-9-]*[0-9]$
See the result here. Trimming spaces looks like $trimmed = str_replace(' ', '', $pattern);
.
How about this regexp:
/^[0-9-+()\s]+$/
See it in action here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With