如何在Javascript中一次验证多个电子邮件?
问题描述:
我正在验证从输入字段中的多个电子邮件,并不能真正让我的正则表达式工作。我有了一个逗号,分号,空格分隔的电子邮件,有时没有空间,像这样的输入域:如何在Javascript中一次验证多个电子邮件?
USER1 @ email.comuser2 @ gmail.com,[email protected] ; [email protected] [email protected]
我试图让使用正则表达式的所有电子邮件,然后确认他们每个人,但真的不知道如何在Javascript中使用正则表达式来做到这一点。
我写我的代码在Java和它在获得所有电子邮件的伟大工程:
Java代码:
String employeeEmails = "[email protected] , [email protected] [email protected];[email protected]";
Matcher eachEmail = Pattern.compile("\\[email protected]\\w+.com").matcher(employeeEmails);
List<String> emailList = new ArrayList<String>();
while (eachEmail.find()){
emailList.add(eachEmail.group());
}
最后的emailList拥有所有的电子邮件
现在我试图通过Javascript获取所有电子邮件并验证其中的每一封电子邮件,如果其中一封电子邮件不是有效的电子邮件,则会引发错误。这里是我的代码:
的Javascript:
var regex1 = /\[email protected]\w+.com/; // This will get all emails from inputField
var emailList = regex1;
var regex2 = /^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/; // This will validate each email
for(var i = 0;i < emailList.length;i++) {
if(!regex2.test(emailList[i])) {
return me.invalidText; // throw error if an email is not valid
}
}
需要得到这个在Javascript中完成的。有谁能告诉我我错过了什么吗?先谢谢你!
答
我希望这可以帮助您:
employeeEmails = "[email protected] , [email protected] [email protected];[email protected]*[email protected]";
function extractEmails(x) { return x.match(/([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})/g); }
var emails=extractEmails(employeeEmails);
// The emails already in an array, now a more exhaustive checking:
function validateEmail(v) { var regex = /^(([^<>()\[\]\\.,;:\[email protected]"]+(\.[^<>()\[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[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 regex.test(v);
}
emails.forEach(function(email, index)
{
// Here you can handle each employee emails.
//
// Example:
var verified=validateEmail(email);
document.write(' validation is '+ verified +' for '+ email +'<br>');
});
来源: