简体   繁体   English

JavaScript电子邮件正则表达式匹配

[英]Javascript email regex matching

Please see the Javascript code below. 请参阅下面的Javascript代码。 The else if block which is doing a check for email pattern is not allowing any of the email ids . else if块正在检查电子邮件模式,不允许任何电子邮件id。 What does the match() function return? match()函数返回什么? Please help. 请帮忙。

Used test() 用过的test()

empty field :working fine wron mail id : working fine Correct email id : not working 空字段:工作正常wron邮件ID:工作正常正确的电子邮件ID:不工作

var pattern = new RegExp("/^(([^<>()[\]\\.,;:\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,}))$/");
   if(!accountantEmail){
       $("#infoTextMsg").hide();
       $("#accountantEmailNoDataErr").show();
       $("#accountantEmailInvalidFormat").hide();
       $("#accountant_email").focus();
       return false;
   }
   else if(!(pattern.test(accountantEmail))){
       $("#accountantEmailInvalidFormat").show();
       $("#infoTextMsg").hide();
       $("#accountantEmailNoDataErr").hide();
       $("#accountant_email").focus();
       return false;
   }

Using regular expressions is probably the best way. 使用正则表达式可能是最好的方法。 Here's an example ( live demo ): 这是一个示例( 实时演示 ):

function validateEmail(email) 
{ 
    var re = /^(([^<>()[\]\\.,;:\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,}))$/;
        return re.test(email);
} 

But keep in mind that one should not rely only upon JavaScript validation. 但是请记住,不应该只依赖JavaScript验证。 JavaScript can easily be disabled. 可以轻松禁用JavaScript。 This should be validated on the server side as well. 这也应该在服务器端进行验证。

Javascript match returns an array containing the matches. Javascript match返回一个包含匹配项的数组。

Here's the regular expression I use: 这是我使用的正则表达式:

var pattern = "[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}";

if(!(accountantEmail.match(pattern))) {
    return false;
}

For validation scenarios, you should use the RegExp#test function. 对于validation方案,应使用RegExp#test函数。

var pattern = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

if (!pattern.test(accountantEmail)) {
    $("#accountantEmailInvalidFormat").show();
    $("#infoTextMsg").hide();
    $("#accountantEmailNoDataErr").hide();
    $("#accountant_email").focus();
    return false;
}

As commented on the other posts, the match function is intended for group capturing. 正如在其他帖子中所评论的那样, match功能旨在用于组捕获。

Also note that you were specifying your pattern with an / on it's beginning. 还要注意,您在pattern的开头指定了/ This isn't necessary if you're specifying a RegExp as a string. 如果将RegExp指定为字符串,则没有必要。

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

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