2

I'm trying to use a regular expression with the Validators.pattern() for Angular 6 FormBuilder, but the validation never goes through. I have tested the RegEx on https://codepen.io/devtips/pen/gzqKKP to see if it was accepted and it did.

The expression I wrote is /^[(0-9)]*[\s][\d]{1,5}-?[\d]{1,5}$/ and the formats I'm trying to validate are (000) 000-0000 and (000) 0000-0000 but my input always shows an invalid result.

buildAgentDetailsForm() {
this.agentDetailForm = this.fb.group({
  FirstName: ['', [Validators.required, Validators.nullValidator]],
  LastName: ['', [Validators.required, Validators.nullValidator]],
  Email: ['', [Validators.required, Validators.email]],
  Phone: [
    '',
    [
      Validators.required,
      Validators.pattern(/^[(0-9)]*[\s][\d]{1,5}-?[\d]{1,5}$/)
    ]
  ],
  EmergencyPhone: ['', [Validators.required]],
  Address: ['', [Validators.required]]
  });
}

Is my expression written in a wrong way? Also I'm using a mask on the input field so it will restrict the input and will include the () and the dash

7
  • what's the type of your input? Is it simply string? I bet it's not but might be wrong Commented Aug 17, 2018 at 20:32
  • 2
    Umh my bad then. No it's fine. Can you create a quick repro on stackblitz? Might be easier to help you out! Commented Aug 17, 2018 at 20:45
  • 1
    It really sounds as if there were some typo in the code. However, a more precise pattern would be /^\(\d{3}\)\s\d{3,4}-\d{4}$/ (as per your sample strings). Commented Aug 17, 2018 at 20:45
  • 1
    Your regex matches the example value and you added it correctly. It should work, so I'd double check the real control value (spaces?). Simple way: window['c'] = this.agentDetailForm Commented Aug 17, 2018 at 20:52
  • 1
    I created a stackblitz and test your validation, it's working fine. It must be your masking or other place that cause the error. stackblitz.com/edit/so-q-ng-val. It must Commented Aug 18, 2018 at 3:55

1 Answer 1

1

Try replacing pattern validator with this: Validators.pattern("[(0-9)]*[\\s][\\d]{1,5}-?[\\d]{1,5}")

Sign up to request clarification or add additional context in comments.

2 Comments

Already tried that, it doesn't give me errors or something about the regex string not being valid, but it just seems the input is not matching it, thus not giving me a valid result

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.