Angular FormBuilder US Phone Number Regex (xxx) xxx-xxxx

Tags: , ,



I am trying to write an Angular Regex validator,

which matches this and only this pattern for phone, spaces exact

(444) 333-2222

How can this be done?

this.productForm = this.formBuilder.group({
  'homephoneNumber': [null, [PhoneUSValidator]],

Working on this Code: Trying to add the space, after the first parenthesis, not sure if correct

export const PhoneUSValidator = Validators.pattern(/^(d{3})d{3}-d{4}$/);

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

/^(d{3}) d{3}-d{4}$/

See the regex demo

Details

  • ^ – start of string
  • ( – a ( char
  • d{3} – three digits
  • ) – a ) char
  • – a space
  • d{3}-d{4} – three digits, hyphen, four digits
  • $ – end of string.


Source: stackoverflow