正则表达式电子邮件验证错误 - 使用JavaScript [英] Regex email verification error - using JavaScript
问题描述
//if HTML5 input email input is not supported
if(type == 'email'){
if(!Modernizr.inputtypes.email){
var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@([a-zA-Z0-9\-])+\.+([a-zA-Z0-9]{2,4})+$/;
if( !emailRegEx.test(value) ){
this.focus();
formok = false;
errors.push(errorMessages.email + nameUC);
return false;
}
}
}
这是我的javascript正则表达式检查电子邮件格式是否正确。但是当我自己尝试它显示没有任何错误.. .. ..它不检查.com或任何结束。我究竟做错了什么?
This is my javascript regex for checking if e-mail format is correct. But When I try it myself it shows no error for any ..@.. It does not check .com or whatever in the end. What am I doing wrong?
推荐答案
您需要使用真正适用于电子邮件地址的正则表达式。你目前的一个是完全破碎的,因为有很多有效的地址不能接受。
You need to use a regex that actually fits for an email address. Your current one is completely broken as there are tons of valid addresses it won't accept.
请参阅 http://www.regular-expressions.info/email.html ,以获得更详细的描述,以及为什么正则表达式毕竟不是一个好主意。
See http://www.regular-expressions.info/email.html for a more detailed description and arguments why a regex is not such a good idea after all.
无论如何,这是一个可能适合您的需求:
Anyway, here's one that probably fits for your needs:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
这是关于这个正则表达式的regular-expressions.info:
Here's what regular-expressions.info says about this regex:
如果我们省略使用双引号和方括号的语法,我们将获得更为实际的RFC 2822实现。今天仍将匹配99.99%的电子邮件地址。
We get a more practical implementation of RFC 2822 if we omit the syntax using double quotes and square brackets. It will still match 99.99% of all email addresses in actual use today.
这篇关于正则表达式电子邮件验证错误 - 使用JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!