Reputation: 348
How can I validate phone field for below format:
(999) 999-9999
I have tried with below, but not working.
if(array_key_exists('phone', $values) && $values['phone'] != '')
{
if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $values['phone']))
{
$form_state->setErrorByName('phone', t('Please enter a valid phone number.'));
}
}
Upvotes: 2
Views: 231
Reputation: 627056
You almost did it: the {3}
should quantify the [0-9]
and the literal parentheses should be added escaped with a backslash:
if(array_key_exists('phone', $values) && !empty($values['phone']))
{
if(!preg_match('/\A\([0-9]{3}\) [0-9]{3}-[0-9]{4}\z/', $values['phone']))
{
$form_state->setErrorByName('phone', t('Please enter a valid phone number.'));
}
}
I also suggest using !empty($values['phone'])
and \A
/ \z
anchors that always match the start / the very end of the string.
See the regex demo:
\A
- unambiguous start of the string anchor\(
- an open parenthesis[0-9]{3}
- 3 digits\)
- a closing parenthesis
- a space[0-9]{3}
- 3 digits-
- a hyphen[0-9]{4}
- 4 digits\z
- the very end of the string.Upvotes: 2