0

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?

Mistalis
  • 17,793
  • 13
  • 73
  • 97
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • You may use `let phoneRegEx = '^\\([1-9]{3}\\)\\s[0-9]{3}-[0-9]{4}$';` and the `^` and `$` can be omitted as they will be added by default. – Wiktor Stribiżew Jan 16 '17 at 20:39
  • 1
    Interesting. I didn't know about the start and end characters. Your adjustments to the regex work as expected. Thank you! – Brandon Taylor Jan 16 '17 at 21:13

1 Answers1

0

I don't Know Angular

But it REGEXP should Work.

\((\d{3})\)\s(\d{3})\-(\d{4})

Result:

Full match  0-14 `(123) 456-7890`
Group 1.    1-4 `123`
Group 2.    6-9 `456`
Group 3.    10-14 `7890`

I'm basically separating each value into a group.

Then u can use

($1) $2-$3

Explanation:

$1 = 123
$2 = 456
$3 = 7890

Note: $0 => Full Match (123) 456-7890