4

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.

1
  • 1
    +1 for using regexlib. Are you sure the previous version had slashes in the string? "/.../" Commented May 20, 2010 at 6:48

2 Answers 2

4

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}$");
Sign up to request clarification or add additional context in comments.

1 Comment

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-].
0

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

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

2 Comments

That was inside a character class, where - means range: [a-z] vs. \d-\d. The regex seems ok.
@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}$/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.