0

I am trying to validate the phone number using regular expression in angular. Using a regex from this reference Regex Ref which suites my requirements.

The regex in the controls pattern is not working, getting this error Cannot read property 'get' of undefined -

this.userForm = this._formBuilder.group({
    firstName: new FormControl('', [
        Validators.required,
        Validators.pattern('^[a-zA-Z ]{1,30}$')
    ]),
    lastName: new FormControl('', [
        Validators.required,
        Validators.pattern('^[a-zA-Z ]{1,30}$')
    ]),
    email: new FormControl('', [
        Validators.required,
        Validators.pattern(
            '[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\\.[a-z]{2,3}'
        )
    ]),
    phoneNumber: new FormControl('', [
        Validators.required,
        Validators.pattern(
            '^(+d{1,2}s?)?1?-?.?s?(?d{3})?[s.-]?d{3}[s.-]?d{4}$' // not working
        )
    ]),
    notes: new FormControl(''),
})
RAHUL KUNDU
  • 745
  • 2
  • 12
  • 33
  • I do not know that error but your pattern need to escape `d`, `s` and `(` like `\d`, `\s` and `\(`. Change `^(+d{1,2}s?)?1?-?.?s?(?d{3})?[s.-]?d{3}[s.-]?d{4}$` to `^\(+\d{1,2}\s?\)?1?-?.?\s?\(?\d{3}\)?[s.-]?\d{3}[s.-]?d{4}$` to prevent error. But you still need correction to work properly. – doctorgu Aug 12 '21 at 04:00
  • @doctorgu, can you share what are the correction I need to make? – RAHUL KUNDU Aug 12 '21 at 04:03
  • For regular expressions it would be best to provide a list of items that the expression needs to match and a list of items that the expression needs to NOT match. Otherwise I could say "look, .* works fine." – AaronJ Aug 12 '21 at 06:21
  • @RAHULKUNDU Aaron is right. If you provide a list of items then someone including me will check it. After you confirmed that your regex is right, you can apply it to your code. If your code is not running with new regex, you can ask again. – doctorgu Aug 12 '21 at 08:03

0 Answers0