开发者

Email regex in JS?

I have a regex that is supposed to match email addresses.

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

When I run the below co开发者_如何学JAVAde in my javascript, it returns null. Could it be an issue with my JS syntax, or is it an issue with the regex?

alert(emailString.match(regex));


This regular expression does not include lowercase letters. Try this:

^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$


Most probably you've forgotten to set the case-insensitive option.

var regex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;

And of course, you're missing lots of valid addresses (.museum etc.)...


The problem with using regex to validate emails is even the expression that is the "standard" misses completely valid addresses. You would be far better off checking to see if it contains the @ symbol and a . . Or to be really fancy you can poll the email address and if no response is given mark it as invalid, this of course comes with an overhead.


Posting a bit late but this regex works 100% across all email formats.

let rEmail = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;

console.log(rEmail.test("john@gmail.com")); //true
console.log(rEmail.test("john@gmail.com123")); //false
console.log(rEmail.test("john.something@gmail.com")); //true
console.log(rEmail.test("john123@gmail.com")); //true


I assume you have not specified the case-insensitive modifier:

var regex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
//                                                    ^

Otherwise the expression only matches upper case letters.


You might want to see RFC 5322, in particular Section 3.4.1


You can use this one. it will support after [dot] 2 ,3 character as per your domain

var email_filter  = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (email_filter.test('yourEmail@gmail.com')) {
  alert('Valid Email');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜