Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I don't know why my regex is incorrect:

var domain = "google.com.br";
var reEmail = new RegExp("^([A-Za-z0-9_-.])+@" + domain + "$");

I need this to validate an email. Example below: reEmail.test("[email protected]");

I get this error:

Range out of order in character class

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

Because you create the RegExp using a String the _-. becomes _-. and that is the invalid range. (It is a range from _ to . and that is not correct)

You need to double escape it:

new RegExp("^([A-Za-z0-9_\-\.])+@" + domain + "$");

That way the \ becomes a in the String and then is used to escape the -in the RegExp.

EDIT:

If you create RegExp by String it is always helpful to log the result so that you see if you did everything right:

e.g. your part of the RegExp

console.log("^([A-Za-z0-9_-.])+@");

results in:

^([A-Za-z0-9_-.])+@

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...