Regex | Verification Error

I am trying to verify a mobile phone number in the USA since I am using the built-in JavaScript validation library that I just replaced this regex validation with the previous version that comes with the validation library.

previous validation regular expression:

"telephone":{ "regex":"/^[0-9\-\(\)\ ]{10,10}$/", "alertText":"* Invalid phone number"}, 

This works like 2126661234 , but not in the US standard.

After I changed:

 "telephone":{ "regex":"/^[2-9]\d{2}-\d{3}-\d{4}$/", "alertText":"* Invalid phone number"}, 

Now every entry gets an error, even if I enter 212-666-1234 . I really don't know what happened, so I'm waiting for some help.

+4
source share
2 answers

You need to avoid backslashes

 "telephone":{ "regex":"/^[2-9]\\d{2}-\\d{3}-\\d{4}$/", "alertText":"* Invalid phone number"}, 

/^[2-9]\d{2}-\d{3}-\d{4}$/ only works in regular expression literals, as in

 var r = /^[2-9]\d{2}-\d{3}-\d{4}$/; 

When you use strings to initialize a regular expression, you should avoid backslashes

 var r = new RegExp("^[2-9]\\d{2}-\\d{3}-\\d{4}$"); 
+4
source

It looks like the original regular expression goes beyond the - sign, for example: \- .

I do not see you doing this in your second example.

0
source

Source: https://habr.com/ru/post/1310332/


All Articles