简体   繁体   English

验证以 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.我想验证一个字符串,它可以是 email 或多个用逗号分隔的电子邮件。

For example:例如:

bill.gates@hotmail.com -> TRUE bill.gates@hotmail.com -> 真
bill -> FALSE账单 -> 假
bill.gates@microsoft.com,steve.jobs@apple.com" -> TRUE bill.gates@microsoft.com,steve.jobs@apple.com" -> 真
bill.gates@microsoft.com,steve.jobs@apple.com, bob" -> false bill.gates@microsoft.com,steve.jobs@apple.com, 鲍勃" -> false
bob,bill.gates@microsoft.com,steve.jobs@apple.com" -> false鲍勃,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;
}

Is this the quickest way to do it?这是最快的方法吗? What if I want to allow;如果我想允许怎么办? and, as separator?并且,作为分隔符?

You shouldn't match top-level domains with [AZ]{2,4} : 您不应将顶级域名与[AZ]{2,4}匹配:

What about .museum or .travel ? 那么.museum.travel怎么样? What about IDNA domains like .xn--0zwm56d or .xn--11b5bs3a9aj6g ? IDNA域名如.xn--0zwm56d.xn--11b5bs3a9aj6g怎么.xn--11b5bs3a9aj6g

Also, it's perfectly valid to have an email-address like "John Doe"@example.org . 此外,拥有像"John Doe"@example.org这样的电子邮件地址是完全有效的。

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. 在服务器端,您可以检查服务器是否存在(您甚至可能想尝试连接到相应的SMTP端口)或只发送验证邮件。

Everything else is prone to errors as the actual regex to check for valid email addresses looks like this . 其他一切都容易出错,因为检查有效电子邮件地址的实际正则表达式是这样的


Also, this 还有,这个

return (regex.test(field)) ? true : false;

is a serious WTF - test() already returns a boolean value! 是一个严重的WTF - test()已经返回一个布尔值!


If you want to allow different separators, use a regular expression instead of a string for splitting, eg 如果要允许不同的分隔符,请使用正则表达式而不是字符串进行拆分,例如

value.split(/,|;/)

Use var result = value.split(",") . 使用var result = value.split(",") You end up with an array. 你最终得到一个数组。

正则表达式:

((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*

In general it is not possible to validate email addresses. 通常, 无法验证电子邮件地址。 Something that is syntactically valid does not necessarily go anywhere, and even if it does whether it will be read. 语法上有效的东西不一定会去任何地方,即使它是否会被阅读。

And even then, covering all the possible syntactically correct addresses (according to the applicable RFC) needs an extremely complex regex (see 1st edition of "Mastering Regular Expressions" (Friedl, O'Reilly) for the 4724 or 6598 character versions, and these probably don't handle IDNs). 即便如此,覆盖所有可能的语法正确的地址(根据适用的RFC)需要一个极其复杂的正则表达式(参见第一版“掌握正则表达式”(Friedl,O'Reilly)的4724或6598字符版本,以及这些可能不处理IDN)。 Eg an apostrophe is a valid character in the local part, and you can have comments inside the email. 例如,撇号是本地部分中的有效字符,您可以在电子邮件中添加注释。

let emails = 'test@gmail.com, test2@gmail.com';

It is very simple.这很简单。 You need to just split your array by comma.您只需要用逗号分隔数组。

By using,通过使用,

const arrayOfEmail = emails.split(',');

Then you should validate the string using regex,然后你应该使用正则表达式验证字符串,

const pattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

// Make common function for check single array pattern
export const validateEmailByString = (email: string) => {
  const emailId = email.replace(/(\r\n|\n|\r| )/gm, ''); // remove blank spaces and new line breaks from string.
  return emailPattern.test(emailId);
}

Then you should just check the emails using,然后你应该使用检查电子邮件,

const isAllEmailValid = arrayOfEmail.every(validateEmailByString);

Thank you.谢谢你。

used this for php preg_match_all() 用于php preg_match_all()

$pattern = '/([\w+\._%-]+@[\w+\.-]+\.[\w+]{2,4}[^,;\s])/';
$text = 'abc@efg.com, efg, hij@emg.com, ak@efg asfbd@efg.com ab@sdfs.com abc+efg@pqr.com';
preg_match_all($pattern, $text, $match);
var_dump($match);

 array(2) { [0] => array(5) { [0] => string(11) "abc@efg.com" [1] => string(11) "hij@emg.com" [2] => string(13) "asfbd@efg.com" [3] => string(11) "ab@sdfs.com" [4] => string(15) "abc+efg@pqr.com" } [1] => array(5) { [0] => string(11) "abc@efg.com" [1] => string(11) "hij@emg.com" [2] => string(13) "asfbd@efg.com" [3] => string(11) "ab@sdfs.com" [4] => string(15) "abc+efg@pqr.com" } } 

try this 试试这个

     function validateEmails(string) {
        var regex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
        var result = string.replace(/\s/g, "").split(/,|;/);        
        for(var i = 0;i < result.length;i++) {
            if(!regex.test(result[i])) {
                return false;
            }
        }       
        return true;
    }

accepts both comma and semicolon as separator, change that if you want only comma as separator 接受逗号和分号作为分隔符,如果只需要逗号作为分隔符,请更改它

如何将字符串拆分成一个数组并循环通过它一次只传递一个电子邮件地址?

I used validationEngine and underscore.js to do this: 我使用validationEngine和underscore.js来做到这一点:

function validateEmail(field, rules, i, options) {
if (!_.all(field.val().split(","), function(candidate) { return $.trim(candidate).match(options.allrules.email.regex); } ))
    return options.allrules.email.alertText;
}

And then decorated my form field with: 然后装饰我的表格字段:

<input class="validate[required,funcCall[validateEmail]]" type="text" name="contact_email" id="contact_email" value=""  />

I would throw an $.trim(result[i]) into that validateMultipleEmailsCommaSeparated function as many people will add the space after their comma. 我会将$.trim(result[i])抛入validateMultipleEmailsCommaSeparated函数,因为很多人会在逗号后添加空格。

Of course that is a jQuery thing so do the equivalent your way. 当然这是一个jQuery的事情,所以你的方式相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM