验证用javascript分隔的多个电子邮件

时间:2022-10-23 16:53:39

I want to validate a string which can be an email or multiple emails separated by commas.

我想验证一个字符串,它可以是电子邮件,也可以是由逗号分隔的多个电子邮件。

For example:

例如:

bill.gates@hotmail.com -> TRUE
bill -> FALSE
bill.gates@microsoft.com,steve.jobs@apple.com" -> TRUE
bill.gates@microsoft.com,steve.jobs@apple.com, bob" -> false
bob,bill.gates@microsoft.com,steve.jobs@apple.com" -> false

-> FALSE bill.gates@microsoft.com,steve.jobs@apple.com" -> TRUE bill.gates@microsoft.com, steve.jobs@microsoft.com " -> FALSE bob,bill.gates@microsoft.com,steve.jobs@apple.com" - bb4 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?

这是最快的方法吗?如果我想允许;作为分隔符?

9 个解决方案

#1


8  

You shouldn't match top-level domains with [A-Z]{2,4}:

您不应该将*域与[A-Z]{2,4}匹配:

What about .museum or .travel? What about IDNA domains like .xn--0zwm56d or .xn--11b5bs3a9aj6g?

去博物馆还是去旅游?那么IDNA的域呢,比如。xn- 0zwm56d或者。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.

其他一切都很容易出错,因为实际的regex检查有效的电子邮件地址是这样的。


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(/,|;/)

#2


3  

Use var result = value.split(","). You end up with an array.

使用var result = value.split(",")。最后得到一个数组。

#3


2  

Regex:

正则表达式:

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

#4


1  

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). E.g. an apostrophe is a valid character in the local part, and you can have comments inside the email.

即使这样,覆盖所有可能的语法正确的地址(根据适用的RFC)也需要一个极其复杂的regex(参见4724或6598字符版本的“精通正则表达式”的第一版(Friedl, O'Reilly),这些可能不能处理idn)。例如,撇号在本地是一个有效字符,你可以在电子邮件中有评论。

#5


0  

How about splitting the string into an array and looping through it passing just one e-mail address at a time?

将字符串分割成一个数组并在其中循环,一次只传递一个电子邮件地址,怎么样?

#6


0  

I used validationEngine and underscore.js to do this:

我使用了validationEngine和下划线。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=""  />

#7


0  

I would throw an $.trim(result[i]) into that validateMultipleEmailsCommaSeparated function as many people will add the space after their comma.

我将在validattipleemailscommparated函数中加入$.trim(result[I]),因为很多人会在逗号后添加空格。

Of course that is a jQuery thing so do the equivalent your way.

当然,这是jQuery的一种做法,所以按您的方式来做。

#8


0  

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"
  }
}

#9


0  

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

接受逗号和分号作为分隔符,如果只需要逗号作为分隔符,则更改该分隔符

#1


8  

You shouldn't match top-level domains with [A-Z]{2,4}:

您不应该将*域与[A-Z]{2,4}匹配:

What about .museum or .travel? What about IDNA domains like .xn--0zwm56d or .xn--11b5bs3a9aj6g?

去博物馆还是去旅游?那么IDNA的域呢,比如。xn- 0zwm56d或者。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.

其他一切都很容易出错,因为实际的regex检查有效的电子邮件地址是这样的。


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(/,|;/)

#2


3  

Use var result = value.split(","). You end up with an array.

使用var result = value.split(",")。最后得到一个数组。

#3


2  

Regex:

正则表达式:

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

#4


1  

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). E.g. an apostrophe is a valid character in the local part, and you can have comments inside the email.

即使这样,覆盖所有可能的语法正确的地址(根据适用的RFC)也需要一个极其复杂的regex(参见4724或6598字符版本的“精通正则表达式”的第一版(Friedl, O'Reilly),这些可能不能处理idn)。例如,撇号在本地是一个有效字符,你可以在电子邮件中有评论。

#5


0  

How about splitting the string into an array and looping through it passing just one e-mail address at a time?

将字符串分割成一个数组并在其中循环,一次只传递一个电子邮件地址,怎么样?

#6


0  

I used validationEngine and underscore.js to do this:

我使用了validationEngine和下划线。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=""  />

#7


0  

I would throw an $.trim(result[i]) into that validateMultipleEmailsCommaSeparated function as many people will add the space after their comma.

我将在validattipleemailscommparated函数中加入$.trim(result[I]),因为很多人会在逗号后添加空格。

Of course that is a jQuery thing so do the equivalent your way.

当然,这是jQuery的一种做法,所以按您的方式来做。

#8


0  

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"
  }
}

#9


0  

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

接受逗号和分号作为分隔符,如果只需要逗号作为分隔符,则更改该分隔符