如何在javascript中验证电子邮件地址?
使用正则表达式可能是最好的方法。你可以在这里看到一系列的测试(取自铬)
1 2 3 4
| function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
} |
下面是接受Unicode的正则表达式示例:
1
| var re = /^(([^<>()\[\]\.,;:\s@"]+(\.[^<>()\[\]\.,;:\s@"]+)*)|(".+"))@(([^<>()[\]\.,;:\s@"]+\.)+[^<>()[\]\.,;:\s@"]{2,})$/i; |
但请记住,不应该只依赖于JavaScript验证。Javascript很容易被禁用。这也应该在服务器端进行验证。
下面是上面的一个例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
var $result = $("#result");
var email = $("#email").val();
$result.text("");
if (validateEmail(email)) {
$result.text(email +" is valid :)");
$result.css("color","green");
} else {
$result.text(email +" is not valid :(");
$result.css("color","red");
}
return false;
}
$("#validate").on("click", validate); |
1 2 3 4 5 6 7 8 9 10 11
| <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
<form>
<p>
Enter an email address:
</p>
<input id='email'>
<button type='submit' id='validate'>Validate!</button>
</form>
<h2 id='result'> |
为了完整起见,这里有另一个符合RFC2822的regex
The official standard is known as RFC 2822. It describes the syntax that valid email addresses must adhere to. You can (but you shouldn't — read on) implement it with this regular expression:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
(...) 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.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
A further change you could make is to allow any two-letter country code top level domain, and only specific generic top level domains. This regex filters dummy email addresses like asdf@adsf.adsf. You will need to update it as new top-level domains are added.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b
So even when following official standards, there are still trade-offs to be made. Don't blindly copy regular expressions from online libraries or discussion forums. Always test them on your own data and with your own applications.
emphasis mine
我稍微修改了一下Jaymon的答案,以满足那些希望通过以下形式进行简单验证的人:
anystring@anystring.anystring
正则表达式:
示例javascript函数:
1 2 3 4 5
| function validateEmail(email)
{
var re = /\S+@\S+\.\S+/;
return re.test(email);
} |
哇,这里很复杂。如果您只想捕获最明显的语法错误,我会这样做:
它通常捕获用户所犯的最明显的错误,并确保表单基本正确,这就是JavaScript验证的全部内容。
当你决定使用正则表达式来验证电子邮件时,你必须理解一些事情:这可能不是一个好主意。一旦你接受了这一点,有很多实现可以让你走到一半,本文就很好地总结了它们。
然而,简而言之,唯一能绝对、肯定地确定用户输入的内容实际上是一封电子邮件,它实际上是发送一封电子邮件,看看会发生什么。除此之外,一切都只是猜测。
HTML5本身具有电子邮件验证功能。如果您的浏览器支持HTML5,那么您可以使用以下代码。
1 2 3
| <form><input type="email" placeholder="me@example.com">
<input type="submit">
</form> |
JSFIDLE链路
根据HTML5规范:
A valid e-mail address is a string that matches the email production of the following ABNF, the character set for which is Unicode.
1 2 3 4 5
| email = 1*( atext /"." )"@" label *("." label )
label = let-dig [ [ ldh-str ] let-dig ] ; limited to a length of 63 characters by RFC 1034 section 3.5
atext = < as defined in RFC 5322 section 3.2.3 >
let-dig = < as defined in RFC 1034 section 3.5 >
ldh-str = < as defined in RFC 1034 section 3.5 > |
This requirement is a willful violation of RFC 5322, which defines a syntax for e-mail addresses that is simultaneously too strict (before the"@" character), too vague (after the"@" character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.
The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.
1
| /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ |
我发现这是最好的解决方案:
1
| /^[^\s@]+@[^\s@]+\.[^\s@]+$/ |
它允许以下格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 1. prettyandsimple@example.com
2. very.common@example.com
3. disposable.style.email.with+symbol@example.com
4. other.email-with-dash@example.com
9. #!$%&'*+-/=?^_`{}|~@example.org
6. "()[]:,;@\\"!#$%&'*+-/=?^_`{}| ~.a"@example.org
7. ""@example.org (space between the quotes)
8. ü????eé@example.com (Unicode characters in local part)
9. ü????eé@ü????eé.com (Unicode characters in domain part)
10. Pelé@example.com (Latin)
11. δοκιμ?@παρ?δειγμα.δοκιμ? (Greek)
12. 我買@屋企.香港 (Chinese)
13. 甲斐@黒川.日本 (Japanese)
14. чебурашка@ящик-с-апельсинами.рф (Cyrillic) |
它显然是通用的,允许所有重要的国际字符,同时仍然强制执行基本的anything@anything.anything格式。它将阻塞RFC在技术上允许的空间,但它们太少了,我很乐意这样做。
在现代浏览器中,您可以使用纯javascript和dom在@sushil答案的基础上构建:
1 2 3 4 5 6 7 8 9
| function validateEmail(value) {
var input = document.createElement('input');
input.type = 'email';
input.required = true;
input.value = value;
return typeof input.checkValidity === 'function' ? input.checkValidity() : /\S+@\S+\.\S+/.test(value);
} |
我在fiddle http://jsfiddle.net/boldewyn/2b6d5/中给出了一个示例。结合了特征检测和Squirtle答案中的裸骨验证,它可以让您从正则表达式大屠杀中解脱出来,并且不会在旧的浏览器中借用。
javascript可以匹配正则表达式:
1
| emailAddress.match( / some_regex /); |
下面是一个用于电子邮件的rfc22正则表达式:
1 2 3 4 5
| ^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*
"\x20*)*(?<))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x
7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<
!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])
[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$ |
这是正确的RFC822版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| function checkEmail(emailAddress) {
var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
var sQuotedPair = '\\x5c[\\x00-\\x7f]';
var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
var sDomain_ref = sAtom;
var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
var sWord = '(' + sAtom + '|' + sQuotedString + ')';
var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
var reValidEmail = new RegExp(sValidEmail);
return reValidEmail.test(emailAddress);
} |
根据RFC正确验证电子邮件地址并不是用一行正则表达式就能实现的。我在PHP中找到的最佳解决方案是什么是有效的电子邮件地址?很明显,它已经移植到了Java。我认为函数太复杂,无法在javascript中移植和使用。javascript/node.js port:https://www.npmjs.com/package/email-addresses。
一个好的实践是在客户机上验证数据,但在服务器上复查验证。考虑到这一点,您可以简单地检查字符串是否像客户机上的有效电子邮件地址,并在服务器上执行严格的检查。
下面是我用来检查字符串是否像有效邮件地址的javascript函数:
1 2 3 4 5
| function looksLikeMail(str) {
var lastAtPos = str.lastIndexOf('@');
var lastDotPos = str.lastIndexOf('.');
return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
} |
说明:
lastAtPos < lastDotPos:最后一个@应该在最后一个.之前,因为@不能是服务器名的一部分(据我所知)。
lastAtPos > 0:在最后一个@之前应该有一些东西(电子邮件用户名)。
str.indexOf('@@') == -1:地址中不应有@@。即使@在电子邮件用户名中显示为最后一个字符,也必须引用它,因此"将介于该@和地址中的最后一个@之间。
lastDotPos > 2:在最后一个点之前至少应该有三个字符,例如a@b.com。
(str.length - lastDotPos) > 2:最后一个点后应有足够的字符组成两字符的域。我不确定支架是否必要。
所有电子邮件地址都包含"at"(即@)符号。测试必要条件:
不要为更复杂的事情烦恼。即使你能很好地确定一封电子邮件是否符合RFC的语法,也不能告诉你它是否属于提供它的人。这才是真正重要的。
要进行测试,请发送验证消息。
这是从http://codesnippets.joyent.com/posts/show/1917窃取的。
1 2 3 4 5 6 7 8
| email = $('email');
filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email.value)) {
// Yay! valid
return true;
}
else
{return false;} |
我真的很期待解决这个问题。所以我修改了上面的电子邮件验证正则表达式
原件/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
被改进的/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()\.,;\s@\"]+\.{0,1})+[^<>()\.,;:\s@\"]{2,})$/
通过维基百科电子邮件地址中的示例。
你可以在这里看到结果。

这样做:
1
| [a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])? |
为什么?它基于RFC2822,这是所有电子邮件地址必须遵守的标准。我不知道你为什么要为"简单"的事情而烦恼…你还是要复制粘贴;)
通常在数据库中存储电子邮件地址时,我会将其设置为小写,实际上,regex通常可以标记为不区分大小写。在这些情况下,这会稍微短一点:
1
| [a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])? |
下面是一个在javascript中使用它的例子(结尾有不区分大小写的标志i)。
1 2
| var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
console.log( emailCheck.test('some.body@domain.co.uk') ); |
注:从技术上讲,有些电子邮件可以在@符号前面的部分中包含引号,引号中包含转义字符(因此,您的电子邮件用户可能会很讨厌,只要是用引号写的,就可以包含@和"..."之类的内容)。从来没有人这样做过!它已经过时了。但是,它包含在真正的RFC2822标准中,这里省略了。
更多信息:http://www.regular-expressions.info/email.html
您不应该使用正则表达式来验证输入字符串,以检查它是否是电子邮件。这太复杂了,不能涵盖所有的案件。
现在,由于您只能覆盖90%的案例,请编写如下内容:
1 2 3
| function isPossiblyValidEmail(txt) {
return txt.length > 5 && txt.indexOf('@')>0;
} |
你可以改进它。例如,"aaa@"是有效的。但总的来说,你知道要点。别被迷住了…简单的90%溶液比100%不起作用的溶液更好。
世界需要更简单的代码…
只需检查输入的电子邮件地址是否有效或不使用HTML。
不需要编写验证函数。
这就是节点验证器的工作原理:
1
| /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/ |
很难得到一个100%正确的电子邮件验证器。唯一真正正确的方法是向帐户发送一封测试电子邮件。也就是说,有一些基本的检查可以帮助确保你得到一些合理的东西。
一些需要改进的地方:
不要使用新的RegExp,只需尝试这样编写RegExp:
其次,检查以确保在@符号之后有一个句点,并确保@和句点之间有字符。
有史以来最好的regex,符合rfc5322
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+
在验证器函数中使用此代码:
1 2 3 4 5 6 7 8
| var emailID = document.forms["formName"]["form element id"].value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
return false;
} |
否则可以使用jquery。内部规则定义:
1 2 3 4
| eMailId: {
required: true,
email: true
} |
2018年Regex更新!试试这个
1 2 3 4
| let val = 'email@domain.com';
if(/^[a-z0-9][a-z0-9-_\.]+@([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val)) {
console.log('passed');
} |
完成typscript版本
1 2
| //
export const emailValid = (val:string):boolean => /^[a-z0-9][a-z0-9-_\.]+@([a-z]|[a-z0-9]?[a-z0-9-]+[a-z0-9])\.[a-z0-9]{2,10}(?:\.[a-z]{2,10})?$/.test(val); |
更多信息https://git.io/vhefc
不检查TLD是否存在的解决方案是不完整的。
几乎所有这些问题的答案都建议使用regex验证电子邮件地址。我认为regex只适用于初步验证。似乎检查电子邮件地址的验证实际上是两个独立的问题:
1-电子邮件格式验证:确保电子邮件是否符合RFC5322中电子邮件的格式和模式,以及TLD是否实际存在。这里可以找到所有有效TLD的列表。
例如,虽然地址example@example.ccc将通过regex,但它不是有效的电子邮件,因为ccc不是IANA的顶级域。
2-确保电子邮件确实存在:为此,唯一的选择是向用户发送电子邮件。
与Squirtle相比,这里有一个复杂的解决方案,但它在正确验证电子邮件方面做得非常出色:
1 2 3
| function isEmail(email) {
return /^((([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.test(email);
} |
使用如下:
1
| if (isEmail('youremail@yourdomain.com')){ console.log('This is email is valid'); } |
显然,就是这样:
1
| /^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i |
摘自10月1日http://fightingforolostcause.net/misc/2006/compare-email-regex.php。
当然,这忽略了国际化。
我对正则表达式的了解不多。这就是为什么我首先用一个简单的正则表达式检查一般语法,然后用其他函数检查更具体的选项。这可能不是最好的技术解决方案,但这样我就更灵活更快了。
我遇到的最常见的错误是空格(尤其是开头和结尾),偶尔还有一个双点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function check_email(val){
if(!val.match(/\S+@\S+\.\S+/)){ // Jaymon's / Squirtle's solution
// Do something
return false;
}
if( val.indexOf(' ')!=-1 || val.indexOf('..')!=-1){
// Do something
return false;
}
return true;
}
check_email('check@thiscom'); // Returns false
check_email('check@this..com'); // Returns false
check_email(' check@this.com'); // Returns false
check_email('check@this.com'); // Returns true |
下面是关于使用正则表达式验证电子邮件地址的非常好的讨论;"比较电子邮件地址验证正则表达式"
以下是当前的top表达式,它与javascript兼容,用于参考:
1
| /^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| <form name="validation" onSubmit="return checkbae()">
Please input a valid email address:<br />
<input type="text" size=18 name="emailcheck">
<input type="submit" value="Submit">
</form>
<script language="JavaScript1.2">
var testresults
function checkemail(){
var str = document.validation.emailcheck.value
var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(str))
testresults = true
else {
alert("Please input a valid email address!")
testresults = false
}
return (testresults)
}
function checkbae(){
if (document.layers || document.getElementById || document.all)
return checkemail()
else
return true
} |
Microsoft在ASP.NET MVC中提供的正则表达式是
1
| /^[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/ |
我把它贴在这里,以防它有缺陷——尽管它总是很适合我的需要。
维基百科标准邮件语法:
https://en.wikipedia.org/wiki/email_-address示例https://fr.wikipedia.org/wiki/adresse_uu3%aElectronique syntax_exacte
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| function validMail(mail)
{
return /^(([^<>()\[\]\.,;:\s@"]+(\.[^<>()\[\]\.,;:\s@"]+)*)|(".+"))@(([^<>()\.,;\s@"]+\.{0,1})+([^<>()\.,;:\s@"]{2,}|[\d\.]+))$/.test(mail);
}
// VALID MAILS
validMail('Abc@example.com') // Return true
validMail('Abc@example.com.') // Return true
validMail('Abc@10.42.0.1') // Return true
validMail('user@localserver') // Return true
validMail('Abc.123@example.com') // Return true
validMail('user+mailbox/department=shipping@example.com') // Return true
validMail('"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com') // Return true
validMail('!#$%&\'*+-/=?^_`.{|}~@example.com') // Return true
validMail('"()<>[]:,;@\\"!#$%&\'-/=?^_`{}| ~.a"@example.org') // Return true
validMail('"Abc@def"@example.com') // Return true
validMail('"Fred Bloggs"@example.com') // Return true
validMail('"Joe.\\Blow"@example.com') // Return true
validMail('Lo?c.Accentué@voilà.fr') // Return true
validMail('""@example.org') // Return true
validMail('user@[IPv6:2001:DB8::1]') // Return true
// INVALID MAILS
validMail('Abc.example.com') // Return false
validMail('A@b@c@example.com') // Return false
validMail('a"b(c)d,e:f;g<h>i[j\k]l@example.com') // Return false
validMail('just"not"right@example.com') // Return false
validMail('this is"not\allowed@example.com') // Return false
validMail('this\ still"not\\allowed@example.com') // Return false
validMail('john..doe@example.com') // Return false
validMail('john.doe@example..com') // Return false |
显示此测试:https://regex101.com/r/lhj9gu/1
如何在Android或Java中编写特定的正则表达式。
1)USER_NAME ="^[A-Za-z0-9_-]{min number of character,max number of character}$";。
2)江户十一〔1〕号
3)江户十一〔2〕。
4)江户十一〔3〕。
5)江户十一〔四〕号
6)江户十一〔5〕。
7)江户十一〔6〕。
8)江户十一〔7〕
9)江户十一〔8〕。
10)江户十一〔9〕
11)江户十一〔10〕。
12)江户十一〔11〕。
13)江户十一〔9〕。
我混合了@mevius和@boldewyn代码来创建这个最终代码,以便使用javascript进行电子邮件验证。
1 2 3 4 5 6 7 8 9 10 11 12
| function ValidateEmail(email){
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var input = document.createElement('input');
input.type = 'email';
input.value = email;
return typeof input.checkValidity == 'function' ? input.checkValidity() : re.test(email);
} |
我在我的博客上共享了这段代码。
Sectrean的解决方案效果很好,但我的线头出了问题。所以我加了一些逃犯:
1 2 3 4
| function validateEmail(email){
var re = /^(([^<>()[]\\.,;:\s@"]+(\.[^<>()[]\\.,;:\s@"]+)*)|(".+"))@(([[0-9]{1,3}\??.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
} |
我在JS中寻找一个通过所有电子邮件地址测试用例的regex:
email@example.com有效邮件
firstname.lastname@example.com电子邮件地址字段中包含点
email@subdomain.example.com电子邮件包含带子域的点
firstname+lastname@example.com加号被认为是有效字符
email@192.0.2.123域是有效的IP地址
IP地址周围的email@[192.0.2.123]方括号被认为是有效的。
电子邮件周围的"email"@example.com报价被认为是有效的。
地址中的1234567890@example.com位有效
域名中的email@domain-one.example破折号有效
地址字段中的_______@example.com下划线有效
email@example.name.name是有效的顶级域名
顶层域名中的email@example.co.jp点也被认为是有效的(此处以co.jp为例)
地址字段中的firstname-lastname@example.com破折号有效
我们走到这里:
http://regexr.com/3f07j
或正则表达式:
1
| Regex = /(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@[*[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+]*/ |
这是我用于前端电子邮件验证的功能。(正则表达式来自parsley.js)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <!DOCTYPE html>
<html>
<head>
Our Company
<style>
.form-style {
color: #ccc;
}
</style>
</head>
<body>
Email Validation Form Example
<input type="text" name="email" id="emailInput" class="form-style">
function validateEmail(emailAddress) {
var regularExpression = /^((([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]))){2,6}$/i;
return regularExpression.test(emailAddress);
}
function showEmailValidationState(event) {
if (validateEmail(event.target.value)) {
document.getElementById("emailInput").style.color = 'black';
}
}
document.getElementById("emailInput").addEventListener("keyup", showEmailValidationState);
</body>
</html> |
The best practice is to either use HTML5 built-in email tag.
1
| <input type="email" name="email"> |
或者使用常见的电子邮件语法来识别@和。下面给出了字符串中的。
1
| ^[a-zA-Z0-9_\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$ |
Note that this would still produce invalid email that will still match
the regex, its almost impossible to catch them all but this will
improve the situation a little.
你也可以试试
1 2 3
| var string ="hmharsh3@gmail.com"
var exp = /(\w(=?@)\w+\.{1}[a-zA-Z]{2,})/i
alert(exp.test(string)) |
以下regex验证:
- 以前没有空格@
- (-)和(.)不应在一起@after@no special characters after@2 characters must before@@电子邮件长度应少于128个字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function validateEmail(email) {
var chrbeforAt = email.substr(0, email.indexOf('@'));
if (!($.trim(email).length > 127)) {
if (chrbeforAt.length >= 2) {
var re = /^(([^<>()[\]{}'^?\\.,!|//#%*-+=&;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
//var re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
return re.test(email);
} else {
return false;
}
} else {
return false;
}
} |
使用正则表达式:
1
| /^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/ |
例子:
1 2 3 4
| function validateEmail(email) {
var re = /^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/;
return re.test(email);
} |
它应该只允许@,., _
1 2 3 4 5 6
| [cc lang="javascript"]
**The personal_info part contains the following ASCII characters.
1.Uppercase (A-Z) and lowercase (a-z) English letters.
2.Digits (0-9).
3.Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
4.Character . ( period, dot or fullstop) provided that it is not the first or last character and it will not come one after the other.** |
*有效电子邮件ID示例*
1 2 3 4 5
| yoursite@ourearth.com
my.ownsite@ourearth.org
mysite@you.me.net
xxxx@gmail.com
xxxxxx@yahoo.com |
1 2 3 4 5 6 7 8
| xxxx.ourearth.com [@ is not present]
xxxx@.com.my [ tld (Top Level domain) can not start with dot"." ]
@you.me.net [ No character before @ ]
xxxx123@gmail.b [".b" is not a valid tld ]
xxxx@.org.org [ tld can not start with dot"." ]
.xxxx@mysite.org [ an email should not be start with"." ]
xxxxx()*@gmail.com [ here the regular expression only allows character, digit, underscore and dash ]
xxxx..1234@yahoo.com [double dots are not allowed |
**javascript邮件代码**函数validateemail(inputText){var mailformat=/^w+([.-]? W+)*@W+([.-]? W+)*(.W 2,3)+$/;if(inputText.value.match(mailformat))。{document.form1.text1.focus();回归真实;}其他的{alert("您输入的电子邮件地址无效!");document.form1.text1.focus();返回错误;}}< /代码>
如果使用闭包,则可以使用内置的goog.format.EmailAddress类型:
http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html
例如:
1
| goog.format.EmailAddress.isValidAddrSpec("blah@blah.com") |
请注意,通过阅读源代码(链接在上面),您可以看到注释状态,即IDN不受支持,它仅用于覆盖大多数地址:
1 2 3 4
| // This is a fairly naive implementation, but it covers 99% of use cases.
// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax
// TODO(mariakhomenko): we should also be handling i18n domain names as per
// http://en.wikipedia.org/wiki/Internationalized_domain_name |
如果您使用的是NG模式和材料,这就完成了工作。
1
| vm.validateEmail = '([a-zA-Z0-9_.]{1,})((@[a-zA-Z]{2,})[\\\.]([a-zA-Z]{2}|[a-zA-Z]{3}))'; |
最好的一个:d(RFC友好,没有错误"太复杂"):
1 2 3 4 5 6 7 8 9 10
| function isMail(mail)
{
pattuser = /^([A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+\.?)*[A-Z0-9_%+\-!#$&'*\/=?^`{|}~]+$/i;
pattdomain = /^([A-Z0-9-]+\.?)*[A-Z0-9-]+(\.[A-Z]{2,9})+$/i;
tab = mail.split("@");
if (tab.length != 2)
return false;
return (pattuser.test(tab[0]) && pattdomain.test(tab[1]));
} |
这是由数千个网站使用的官方Rails指南建议的验证的javascript翻译:
1
| /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i |
相对简单,但针对最常见错误进行测试。
在数千封电子邮件的数据集上测试,它没有错误的否定/肯定。
示例用法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| const emailRegex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
emailRegex.test('email@example.com'); // true
// Multi-word domains
emailRegex.test('email@example.co.uk'); // true
emailRegex.test('email@mail.gmail.com'); // true
// Valid special characters
emailRegex.test('unusual+but+valid+email1900=/!#$%&\'*+-/=?^_`.{|}~@example.com') // true
// Trailing dots
emailRegex.test('email@example.co.uk.'); // false
// No domain
emailRegex.test('email@example'); // false
// Leading space
emailRegex.test(' email@example.com'); // false
// Trailing space
emailRegex.test('email@example.com '); // false
// Incorrect domains
emailRegex.test('email@example,com '); // false
// Other invalid emails
emailRegex.test('invalid.email.com') // false
emailRegex.test('invalid@email@domain.com') // false
emailRegex.test('email@example..com') // false |
这个问题比乍一看更难回答。
世界各地有很多人在寻找"regex来统治他们所有人",但事实上,电子邮件提供商的语气是有的。
怎么了?嗯,"a_z%@gmail.com不能存在,但它可能通过另一个提供者"a_uuz@provider.com存在这样的地址。
为什么?根据RFC:https://en.wikipedia.org/wiki/email_-address rfc_规范。
我将摘录一段,以便于演讲:
1 2 3 4 5 6 7 8 9
| The local-part of the email address may use any of these ASCII characters:
- uppercase and lowercase Latin letters A to Z and a to z;
- digits 0 to 9;
- special characters !#$%&'*+-/=?^_`{|}~;
- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but"John..Doe"@example.com is allowed);[6]
Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.
- space and"(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com. |
所以,我可以拥有这样的电子邮件地址:
1
| A__z/J0hn.sm{it!}h_comment@example.com.co |
如果你尝试这个地址,我敢打赌它将失败在所有或主要部分的regex张贴在整个网络。但请记住,这个地址遵循RFC规则,所以它是公平有效的。
想象一下,我对不能在任何地方注册这些regex感到沮丧!!
唯一真正能够验证电子邮件地址的人是电子邮件地址的提供者。
怎么处理呢?
在几乎所有情况下,用户是否添加了无效的电子邮件并不重要。您可以依赖运行在RFC附近的HTML5 input type="email",几乎没有失败的机会。html5 input type="email"信息:https://www.w3.org/tr/2012/wd-html-markup-20121011/input.email.html
例如,这是一封有效的RFC电子邮件:
1
| "very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com |
但HTML5验证将告诉您,@之前的文本不能包含"或()字符,例如,这实际上是不正确的。
无论如何,您应该通过接受电子邮件地址并向该电子邮件地址发送电子邮件消息来完成此操作,并使用用户必须访问的代码/链接来确认有效性。
这样做的一个好方法是输入"再次输入电子邮件",以避免用户输入错误。如果这还不够,请添加一个标题为"这是您当前的电子邮件吗?"的预提交模式窗口。,然后用户在h2标签中输入的邮件,您知道,为了清楚地显示他们输入的电子邮件,然后是"是,提交"按钮。
如果您希望使用jquery并希望使用现代方法,那么使用jquery输入掩码进行验证。
http://bseth99.github.io/projects/jquery-ui/5-jquery-masks.html
下面演示jquery输入掩码的简单性:http://codepen.io/anon/pen/gprybp
日期的简单输入掩码示例例如未完全验证
1
| <input id="date" type="text" placeholder="YYYY-MM-DD"/> |
剧本:
1 2 3
| $("#date").mask("9999-99-99",{placeholder:"YYYY-MM-DD
<hr>[cc lang="javascript"] <input type="email" class="form-control" required="required" placeholder="Email Address" name="Email" id="Email" autocomplete="Email">
<button class="btn-1 shadow-0 full-width" type="button" id="register">Register account</button> |
1 2 3 4 5 6 7 8
| $("#register").click(function(){
var rea = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var Email = $("#Email").val();
var x = rea.test(Email);
if (!x) {
alert('Type Your valid Email');
return false;
} |
下面是一个简单的regex,它只检查电子邮件的基本格式,例如X@Y.C:
\S+@\S+\.\S+
如果使用angularJS,只需将type="email"添加到输入元素:
https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
如果没有输入元素,可以动态创建:
1 2 3 4 5 6
| var isEmail = $compile('<input ng-model="m" type="email">')($rootScope.$new()).
controller('ngModel').$validators["email"];
if (isEmail('email@gmail.com')) {
console.log('valid');
} |
这里有一些复杂的regex,也可以工作。
我测试过这个,它也能工作:
1
| [a-zA-Z0-9._]+[@]+[a-zA-Z0-9]+[.]+[a-zA-Z]{2,6} |
请在此测试:http://www.regextester.com/?FAM=97334
希望这有帮助。
在nodejs中,您也可以使用validator节点模块,并简单地这样使用
使用NPM安装验证程序安装库
1 2 3
| var validator = require('validator');
validator.isEmail('foo@bar.com'); //=> true |
不管是谁在使用@pvl解决方案并希望它传递eslint prefer模板,下面是一个我使用模板文本而不是字符串串联的版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| validateEmail(email) {
let sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
let sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
let sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
let sQuotedPair = '\\x5c[\\x00-\\x7f]';
let sDomainLiteral = `\\x5b(${sDtext}|${sQuotedPair})*\\x5d`;
let sQuotedString = `\\x22(${sQtext}|${sQuotedPair})*\\x22`;
let sDomainRef = sAtom;
let sSubDomain = `(${sDomainRef}|${sDomainLiteral})`;
let sWord = `(${sAtom}|${sQuotedString})`;
let sDomain = `${sSubDomain}(\\x2e${sSubDomain})*`;
let sLocalPart = `${sWord}(\\x2e${sWord})*`;
let sAddrSpec = `${sLocalPart}\\x40${sDomain}`; // complete RFC822 email address spec
let sValidEmail = `^${sAddrSpec}$`; // as whole string
let reValidEmail = new RegExp(sValidEmail);
return reValidEmail.test(email);
} |
现在,ReactNative版本0.46使用下面的代码进行电子邮件验证。
1 2 3 4 5 6 7
| validateEmail = (email) => {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(email)) {
} else {
alert('email: ' +"Please enter valid emailID.")
}
} |
此regexp可防止重复域名,如abc@abc.com.com.com,它只允许两次域,如abc@abc.co.in。它也不允许从123abc@abc.com这样的号码进行串接。
1
| regexp: /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\@(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/, |
祝你一切顺利!!!!!!!
如何创建一个函数,用javascript中的正则表达式根据电子邮件的模式测试任何字符串,正如我们知道的,电子邮件地址在不同的地区可能会有很大的不同,比如在英国和澳大利亚,它通常以.co.uk或.com.au结尾,所以我也试着覆盖它们,同时检查传递给函数,类似于:
1 2 3
| var isEmail = function(str) {
return typeof str==='string' && /^[\w+\d+._]+\@[\w+\d+_+]+\.[\w+\d+._]{2,8}$/.test(str);
} |
并检查是否是电子邮件,如下所示:
1 2 3 4 5 6 7 8 9
| isEmail('alex@example.com'); //true
isEmail('alireza@test.co.uk'); //true
isEmail('peter.example@yahoo.com.au'); //true
isEmail('alex@example.com'); //true
isEmail('peter_123@news.com'); //true
isEmail('hello7___@ca.com.pt'); //true
isEmail('example@example.co'); //true
isEmail('hallo@example.coassjj#sswzazaaaa'); //false
isEmail('hallo2ww22@example....caaaao'); //false |
以下regex验证:
- 以前没有空格@
- (-)和(.)不应在@
- @2字符后不能有特殊字符@
电子邮件长度应少于128个字符
1 2 3 4 5 6 7 8 9 10 11 12 13
| function validateEmail(email) {
var chrbeforAt = email.substr(0, email.indexOf('@'));
if (!($.trim(email).length > 127)) {
if (chrbeforAt.length >= 2) {
var re = /^(([^<>()[\]{}'^?\\.,!|//#%*-+=&;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
return re.test(email);
} else {
return false;
}
} else {
return false;
}
} |
我知道它不是雷杰克斯,但无论如何…
这是node和npm包电子邮件存在的示例,这是最终检查电子邮件是否存在以及其格式是否正确的示例:)
这将ping电子邮件,如果它的响应,如果没有响应,它将返回false或true。
1 2 3 4 5 6 7 8 9 10 11
| function doesEmailExist(email) {
var emailExistence = require('email-existence');
return emailExistence.check(email,function (err,status) {
if (status) {
return status;
}
else {
throw new Error('Email does not exist');
}
});
} |
以下是MDN上HTML5的建议regex模式:
Browsers that support the email input type automatically provide validation to ensure that only text that matches the standard format for Internet e-mail addresses is entered into the input box. Browsers that implement the specification should be using an algorithm equivalent to the following regular expression:
1 2
| /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}
[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/ |
https://developer.mozilla.org/en-us/docs/web/html/element/input/email验证
我就是这样做的。我使用match()来检查标准的电子邮件模式,并在输入文本中添加一个类来相应地通知用户。希望有帮助!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| $(document).ready(function(){
$('#submit').on('click', function(){
var email = $('#email').val();
var pat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (email.match(pat)){
$('#email')
.addClass('input-valid');
return false;
} else {
$('#email')
.addClass('input-error')
.val('');
return false;
}
});
}); |
1 2 3 4 5 6 7 8 9
| .input-error {
border: 1px solid red;
color: red;
}
.input-valid {
border: 1px solid green;
color: green;
} |
1 2 3 4 5
| <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
<form>
<input type="text" id="email" placeholder="name@service.xx" class="">
<input type="submit" id="submit" value="Send"/>
</form> |
这对我很有用:
1 2 3 4 5 6 7 8 9
| function Email(mail)
{
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("Invalid email address!")
return (false)
} |
个人信息部分包含以下ASCII字符。
大写(A-Z)和小写(A-Z)英文字母。数字(0~9)。
角色!#$ ;%&;'*+-/=nbsp;?^ {{}}
性格。(句点、句点或句点)前提是它不是第一个或最后一个字符,它不会一个接一个出现。
域名[例如com、org、net、in、us、info]部分包含字母、数字、连字符和点。
1 2 3 4 5 6 7 8 9
| function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
} |
我写了一个javascript电子邮件验证器,它与PHP的filter_var($value, FILTER_VALIDATE_EMAIL)实现完全兼容。
https://github.com/mpyw/filter_validate_email.js
1 2 3 4
| import validateEmail from 'filter-validate-email'
const value = '...'
const result = validateEmail(value) |
相当于:
1 2 3 4
| <?php
$value = '...';
$result = (bool)filter_var($value, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE); |
您也可以使用新的regex类,并这样做:
const validaEmail = function validateEmail(str) {
let regex = new RegExp(/([\w\.\-_]+)?\w+@[\w-_]+(\.\w+){1,}/,'igm')
return regex.test(str);
}
参考文献:https://developer.mozilla.org/en-us/docs/web/javascript/guide/regular_表达式
下面是一个有效的解决方案,它以一种形式包含验证/通知功能:
你可以在这个链接上运行它
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| (function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('needs-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
}
form.classList.add('was-validated');
event.preventDefault();
}, false);
}, false);
})(); |
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <p class='title'>
Email validation
<hr size="30px;">
</p>
<form id="needs-validation" novalidate>
<p class='form_text'>Try it out!
</p>
<input type="email" class="form-control" placeholder="Email Address" required>
Please enter a valid email address.
<button type="submit"
class="btn btn-default btn-block">Sign up now
</button>
</form> |
您可以使用https://github.com/chriso/validator.js,只需执行以下操作:
1 2 3
| var validator = require('validator');
validator.isEmail('foo@bar.com'); //=> true |
注意,这可以在客户机上工作。
1 2 3 4 5 6 7 8 9
| function ValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email address!")
return (false)
} |
参考网址:https://www.w3resource.com/javascript/form/email-validation.php
ES6样品
1
| const validateEmail=(email)=> /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email); |
1
| \b[a-z][\w\d_\.]+@\w+\.[a-z]{2}[a-z]?\.?[a-z]{,2}\s |
它允许:
1 2 3 4
| abcxyz123@qwert.com
abc123xyz@asdf.co.in
abc1_xyz1@gmail1.com
abc.xyz@gmail.com.in |
我想加一个关于非ASCII字符的简短说明。Rnevius(和Co.)的解决方案非常出色,但它允许添加西里尔文、日语、表情符号和其他Unicode符号,这些符号可能受到某些服务器的限制。
下面的代码将打印true,尽管它包含utf-8字符Ё。
1
| console.log (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test ('Ё@example.org')) |
在我的情况下,所有非ASCII符号都被禁止,因此我修改了原始表达式以排除U+007F以上的所有字符:
1
| /^(([^\u0080-\uffff<>()\[\]\\.,;:\s@"]+(\.[^\u0080-\uffff<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ |
也许这将有助于防止不受欢迎的行为。
如果将正则表达式定义为字符串,则需要对所有反斜杠进行转义,因此不应使用'w',而应使用'w'。
或者,将其定义为正则表达式:
1
| var pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; |
这是我的电子邮件验证器版本。该代码面向面向面向OOP,用静态方法实现为类。您将发现两个版本的验证器:strict(EmailValidator.validate和kind(EmailValidator.validateKind)。如果电子邮件无效,则首先抛出错误,否则返回电子邮件。第二个返回布尔值,表示电子邮件是否有效。在大多数情况下,我更喜欢严格的版本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| export class EmailValidator {
/**
* @param {string} email
* @return {string}
* @throws {Error}
*/
static validate(email) {
email = this.prepareEmail(email);
const isValid = this.validateKind(email);
if (isValid)
return email;
throw new Error(`Got invalid email: ${email}.`);
}
/**
* @param {string} email
* @return {boolean}
*/
static validateKind(email) {
email = this.prepareEmail(email);
const regex = this.getRegex();
return regex.test(email);
}
/**
* @return {RegExp}
* @private
*/
static getRegex() {
return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
}
/**
* @param {string} email
* @return {string}
* @private
*/
static prepareEmail(email) {
return String(email).toLowerCase();
}
} |
要验证电子邮件,您可以使用以下方法:
1 2 3 4 5 6 7
| // First way.
try {
EmailValidator.validate('balovbohdan@gmail.com');
} catch (e) {
console.error(e.message);
} |
1 2 3 4 5 6 7 8 9
| // Second way.
const email = 'balovbohdan@gmail.com';
const isValid = EmailValidator.validateKind(email);
if (isValid)
console.log(`Email is valid: ${email}.`);
else
console.log(`Email is invalid: ${email}.`); |
我的一个同事和我分享了这个regex。我非常喜欢。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function isValidEmailAddress (email) {
var validEmail = false;
if (email) {
email = email.trim().toLowerCase();
var pattern = /^[\w-']+(\.[\w-']+)*@([a-zA-Z0-9]+[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*?\.[a-zA-Z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/;
validEmail = pattern.exec(email);
}
return validEmail;
}
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
} |
电子邮件ID的简单regex
1
| String EMAIL_PATTERN ="^(([^<>()\[\]\.,;:\s@"]+(\.[^<>()\[\]\.,;:\s@"]+)*)|(".+"))@(([^<>()[\]\.,;:\s@"]+\.)+[^<>()[\]\.,;:\s@"]{2,})$"; |
在JavaScript中非常简单。请遵循此代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function validate(){
var email = document.getElementById('Email');
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value))
{
alert('Please Enter the valid email address');
email.focus;
return false;
}
else
{
return true;
} |
HTML代码:
1 2 3 4 5 6 7 8
| form name="form"
enctype="multipart/form-data"
name="form"
action="register.php"
method="POST" onsubmit="return validate();">
<input type="text" placeholder="Enter ur Email Id" id="Email" name="Email" />
<input type="submit" id="submit" value="save" name="Like" class="button" />
</form> |
1 2 3 4 5 6 7 8 9 10
| function validatecontactEmail(email) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
{
return (true)
}
return (false)
} |
遵循正则表达式:
1
| /^([\w]+)(.[\w]+)*@([\w]+)(.[\w]{2,3}){1,2}$/; |
电子邮件验证regex:
1 2 3 4 5 6 7 8 9 10 11
| var rex_email = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(email=="") {
window.plugins.toast.showShortBottom("Please enter the details.", function(a) {
console.log('toast success: ' + a);
}, function(b) { });
} else if(!rex_email.test(email)) {
window.plugins.toast.showShortBottom("Please enter the valid email id.", function(a) {
console.log('toast success: ' + a);
}, function(b) { });
} |
W3Schools提供了一个简单有效的脚本来验证电子邮件:
1 2 3 4 5 6 7 8 9
| function validateEmail(email) {
var atpos=email.indexOf("@");
var dotpos=email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.length) {
alert("Not a valid e-mail address");
return false;
}
return true;
} |
请注意,如果存在空格,则必须删除空格,如下所示:
来源:javascript表单验证
1 2 3 4
| function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._]+[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
} |
如果电子邮件地址有效,则返回true。否则,它将返回false。