views:

41

answers:

2

I'm trying to validate a USA mobile number, since I'm using pre-built javascript validation library I just replaced this regex validation with the previous one which comes with the validation library.

previous validation regex:

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

This works like 2126661234 but not in USA standard.

After I changed:

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

Now every entry I get an error even if I enter 212-666-1234 I really don't know what is the wrong, so I'm expecting some help.

A: 

Looks like the original regex escapes the - sign, like this: \-.

I don't see you doing that in your second example.

Eric Eijkelenboom
That was inside a character class, where `-` means range: `[a-z]` vs. `\d-\d`. The regex seems ok.
Kobi
So then what's the issue?
MMRUser
@Kobi, MMRUser: The _second_ dash in example 1 is escaped with a backslash, that is not related to the range a-z. So, I'm saying that maybe your regex should look like this: /^[2-9]\d{2}\-\d{3}\-\d{4}$/
Eric Eijkelenboom
+3  A: 

You need to escape the backslashes

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

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

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

When you are using strings to initialize regex, you should escape the backslashes

var r = new RegExp("^[2-9]\\d{2}-\\d{3}-\\d{4}$");
Amarghosh
Good catch. This also explains why the original *seemed* to work; it looked like `[0-9-() ]` - JavaScript strings tend to ignore wrongly escaped characters, and `-` became literal after a range, much like `[a-z-]`.
Kobi
Thanks it worked..
MMRUser