I am trying to write an Angular Regex validator,
which matches this and only this pattern for phone, spaces exact
JavaScript
x
2
1
(444) 333-2222
2
How can this be done?
JavaScript
1
3
1
this.productForm = this.formBuilder.group({
2
'homephoneNumber': [null, [PhoneUSValidator]],
3
Working on this Code: Trying to add the space, after the first parenthesis, not sure if correct
JavaScript
1
2
1
export const PhoneUSValidator = Validators.pattern(/^(d{3})d{3}-d{4}$/);
2
Advertisement
Answer
You need to
- Add a literal space (or
s
to allow any whitespace) exactly at the location where you expect it to be in the string - Escape the
(
char after^
because you need to match a literal open parenthesis. - Do not escape
-
that is outside of a character class, i.e. not inside[...]
.
You may use
JavaScript
1
2
1
/^(d{3}) d{3}-d{4}$/
2
See the regex demo
Details
^
– start of string(
– a(
chard{3}
– three digits)
– a)
chard{3}-d{4}
– three digits, hyphen, four digits$
– end of string.