我結束了使用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