这是我的正则表达式:
var emailsRegex = /^[\W]*([\w+\-.%]+@[\w\-.]+\.[A-Za-z]{2,4}[\W]*;{1}[\W]*)*([\w+\-.%]+@[\w\-.]+\.[A-Za-z]{2,4})[\W]*$/;
目前,它允许完全限定的单个电子邮件和多个以分号分隔的电子邮件,例如:
email1@hi.com
email1@hi.com; email2@hi.com
email1@hi.com; email2@hi.com; email3@hi.com
...都是有效的。
我希望它保持不变,但也允许空白/空输入。即使在输入字段中未指定required
属性,我的表单也会使用空白输入字段标记$ invalid。
我怀疑这是因为它没有通过正则表达式验证。谢谢!
答案 0 :(得分:4)
Please do not use a regex to match an email。首先,你的正则表达式是错误的(它不会匹配像foo+bar@example.org
那样的电子邮件,这对于RFC822和更新的RFC来说是完全有效的。您最好使用verifyjs或fogcreek's email checker等库来检查该电子邮件。
然后,您所要做的就是使用email_string.split(';')
在每封电子邮件中拆分字符串,并在每个电子邮件上应用检查器。
HTH
答案 1 :(得分:-1)
我最终使用了string.split(;),然后通过了一个改进的RegEx,它应占今天使用的99%的电子邮件地址。我正在Angular Directive中做这件事。
它允许空输入,多个以;
分隔的电子邮件,这些电子邮件符合RFC,主要用于电子邮件地址。
HTML
<input type="text" id="emailCc" name="emailCc" ng-model="vm.ccRecipient" class="form-control input-sm" multiple-emails="vm.ccRecipient" placeholder="Email Cc" />
AngularJS
angular.module('my-app')
.directive('multipleEmails', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (rawInput) {
var emails = rawInput.split(';');
//console.log(emails);
// Consider not using complex regex validation for emails. See: https://davidcel.is/posts/stop-validating-email-addresses-with-regex/
// Instead, consider just checking for an "@" and a "." and call it a done. The mail daemon will return whether its a valid or invalid/bounced email address
//var emailsRegex = /.+@.+\..+/i;
// define single email validator here
var regexPattern = /^(([^<>()\[\]\\.,;:\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,}))$/;
// angular.foreach(emails, function() {
var validityArr = emails.map(function (str) {
if (rawInput) {
return regexPattern.test(str.trim());
} else if (!rawInput) {
return true;
}
}); // sample return is [true, true, true, false, false, false]
//console.log(emails, validityArr);
var atLeastOneInvalid = false;
angular.forEach(validityArr, function (value) {
if (value === false)
atLeastOneInvalid = true;
});
if (!atLeastOneInvalid) {
// ^ all I need is to call the angular email checker here, I think.
ctrl.$setValidity('multipleEmails', true);
return rawInput;
} else {
ctrl.$setValidity('multipleEmails', false);
return undefined;
}
});
}
};
});