Regex | validation error
I'm trying to validate a USA mobile number, since I'开发者_JAVA技巧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.
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}$");
Looks like the original regex escapes the -
sign, like this: \-
.
I don't see you doing that in your second example.
精彩评论