How to resolve reg expression in angular 6

63 Views Asked by At

I am trying to validate phone number in the reactive form validation. but reg expression not working properly. Getting error like below:

ERROR
Error: Invalid regular expression: /^/^+([0-9]{1,3})?[- ]?(d{3})?[- ]?(d{3})[- ]?(d{4,6})( ext d{4})?$/$/: Nothing to repeat

Demo: https://stackblitz.com/edit/angular-g7vtuj-onr6bz?file=app%2Fselect-multiple-example.ts

3

There are 3 best solutions below

1
On

You should remove the extra forward slashes / at the beginning and end of the regular expression pattern. Also there is a typo in the regular expression; \d should be used instead of d for digit matching.

I hope it helps.

5
On

There are a couple of issues with your regular expression.

The main one is that + has special meaning in a regular expression and needs to be escaped. This will make the regexp valid but it still won't work.

d{3} will match exactly "ddd" (three literal "d" characters) to match a multiple digits you will need to use \d{3}.

After doing this your regular expression should look like

Validators.pattern(
        '/^\\+([0-9]{1,3})?[- ]?(\\d{3})?[- ]?(\\d{3})[- ]?(\\d{4,6})( ext \\d{4})?$/'
      ),
0
On

Validators.pattern( /^+([0-9]{1,3})?[- ]?(\d{3})?[- ]?(\d{3})[- ]?(\d{4,6})( ext \d{4})?$/ ),

use this corrected pattern. reported issue are as below:

  1. Removed the extra ^ at the beginning and the extra $ at the end.

  2. Changed d to \d for digit matching.