使用javascript验证多个电子邮件逗号分隔 [英] Validate Multiple Emails Comma Separated with javascript
问题描述
我想验证一个字符串,该字符串可以是电子邮件或多个用逗号分隔的电子邮件。
I want to validate a string which can be an email or multiple emails separated by commas.
例如:
bill.gates@hotmail.com - > TRUE
bill - > FALSE
bill.gates @ microsoft.com,steve.jobs @ apple.com - > TRUE
bill.gates @ microsoft.com,steve.jobs @ apple.com,bob - > false
bob,bill.gates @ microsoft.com,steve.jobs @ apple.com - > false
bill.gates@hotmail.com -> TRUE
bill -> FALSE
bill.gates@microsoft.com,steve.jobs@apple.com" -> TRUE
bill.gates@microsoft.com,steve.jobs@apple.com, bob" -> false
bob,bill.gates@microsoft.com,steve.jobs@apple.com" -> false
我推出了下一个适用于测试用例的代码。
I came out with the next code which works with the test cases.
function validateEmail(field) {
var regex=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
return (regex.test(field)) ? true : false;
}
function validateMultipleEmailsCommaSeparated(value) {
var result = value.split(",");
for(var i = 0;i < result.length;i++)
if(!validateEmail(result[i]))
return false;
return true;
}
这是快车吗? st方式做到了吗?如果我想允许怎么办并且,作为分隔符?
Is this the quickest way to do it? What if I want to allow ; and , as separator?
推荐答案
您不应将顶级域名与 [AZ] {匹配2,4}
:
.museum
或。旅行
?那些IDNA域如 .xn - 0zwm56d
或 .xn - 11b5bs3a9aj6g
?
What about .museum
or .travel
? What about IDNA domains like .xn--0zwm56d
or .xn--11b5bs3a9aj6g
?
此外,拥有像John Doe@ example.org
这样的电子邮件地址是完全有效的。
Also, it's perfectly valid to have an email-address like "John Doe"@example.org
.
在我看来,你应该在客户端检查的是,地址是否包含 @
以及是否至少有一个。
之后。在服务器端,您可以检查服务器是否存在(您甚至可能想尝试连接到相应的SMTP端口)或只发送验证邮件。
In my opinion, all you should check on the client side is if the address contains an @
and if there's at least one .
after it. On the server side, you could check if the server exists (you might even want to try connecting to the appropriate SMTP port) or just send out a validation mail.
所有内容否则很容易出错,因为实际的正则表达式会检查有效的电子邮件地址像这样。
Everything else is prone to errors as the actual regex to check for valid email addresses looks like this.
此外,这
return (regex.test(field)) ? true : false;
是一个严重的WTF - test()
已经返回一个布尔值!
is a serious WTF - test()
already returns a boolean value!
如果要允许不同的分隔符,请使用正则表达式而不是字符串进行拆分,例如
If you want to allow different separators, use a regular expression instead of a string for splitting, eg
value.split(/,|;/)
这篇关于使用javascript验证多个电子邮件逗号分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!