我结束了使用string.split(;),然后经过改进的正则表达式应该在今天使用的占电子邮件地址的99%。我正在Angular指令中做这件事。
它允许空输入,由;
分隔的多个电子邮件符合大多数电子邮件地址使用的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 = /[email protected]+\..+/i;
// define single email validator here
var regexPattern = /^(([^<>()\[\]\\.,;:\[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,}))$/;
// 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;
}
});
}
};
});
试试这个/([^您正则表达式,] \/*/g的 –
作为一个答案的状态,用一个正则表达式验证电子邮件是充满了危险。你最多应该检查以确保存在一个'@'。之后,验证地址的唯一方法是发送电子邮件 – Brennan
我喜欢这个想法来检查'@'和'.' - 并且也允许为空 - 这个正则表达式是什么?'/[email protected]+\..+/我工作,但它仍然不允许em PTY。 – TetraDev