I'm working with a form for US phone numbers:
let phoneRegEx = '^\([1-9]{3}\)\s{1}[0-9]{3}-[0-9]{4}$';
class PhoneFormComponent {
...
buildForm(): void {
this.form = this.formBuilder.group({
number: [
this.phone ? this.phoneNumberPipe.transform(this.phone.number) : '', [
Validators.required,
Validators.pattern(phoneRegEx),
]
]
});
}
}
I also have a Pipe that formats the phone number to my liking:
@Pipe({name: 'phoneNumber'})
export class PhoneNumberPipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
let areaCode = value.substring(0, 3);
let prefix = value.substring(3, 6);
let number = value.substring(6);
return `(${areaCode}) ${prefix}-${number}`;
}
}
Phone numbers numbers are stored as a string with no spaces or formatting in the API that I am required to access, so I'm leveraging the pipe to format the phone number as provided by the service when populating the form, and then matching the same pattern for input. I strip out the formatting when supplying the value back to the API.
According to regex101.com, my regex should be working as expected: https://regex101.com/r/9TRysJ/1, e.g. (111) 111-1111 should be valid.
However, my Angular form always reports that the value for the phone field is invalid. What am I doing wrong?