如何使用jQuery验证来验证电子邮件?

mos*_*toh 1 jquery jquery-validate

我的脚本javascript是这样的:

email: {
         required: true,
         email: true          
},
Run Code Online (Sandbox Code Playgroud)

在文本字段中的电子邮件中,我写了:chelsea@gmail没有.com,它是有效的。

有什么解决方案可以解决我的问题吗?

谢谢

Ang*_*tis 5

编辑答案:

要验证电子邮件地址是否为name@domain.tld格式,可以使用以下正则表达式:

var emailExp = new RegExp(/^\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i);
Run Code Online (Sandbox Code Playgroud)

此正则表达式仅接受包含@符号,点和2-4个字符长的TLD的电子邮件地址。

您可以使用上面的正则表达式来验证给定的电子邮件地址,如下所示:

function validate_email (email) {
   /* Define the recommended regular expression. */
   var emailExp = new RegExp(/^\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i);

   /* Test the email given against the expression and return the result. */
   return emailExp.test(email);
}
Run Code Online (Sandbox Code Playgroud)

jQuery验证程序:

jQuery Validator不支持使用正则表达式,而是在内部使用默认的HTML5电子邮件正则表达式,因此您必须首先为验证器创建一个新方法来执行此操作:

$.validator.addMethod(
    /* The value you can use inside the email object in the validator. */
    "regex",

    /* The function that tests a given string against a given regEx. */
    function(value, element, regexp)  {
        /* Check if the value is truthy (avoid null.constructor) & if it's not a RegEx. */
        if (regex && regexp.constructor != RegExp) {
           /* Create a new regular expression using the regex argument. */
           regexp = new RegExp(regexp);
        }

        /* Check whether the argument is global and, if so set its last index to 0. */
        else if (regexp.global) regexp.lastIndex = 0;

        /* Return whether the element is optional or the result of the validation. */
        return this.optional(element) || regexp.test(value);
    }
);
Run Code Online (Sandbox Code Playgroud)

现在已经为验证器创建了一个支持对正则表达式进行验证的方法,您可以使用jQuery.validate以下方法:

$('#element_id').validate({
    email: {
        required: true,
        email: true,
        regex: /^\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
    }
});
Run Code Online (Sandbox Code Playgroud)

原始答案(改进)

要过滤电子邮件地址并仅接受类似name@domain.tld这样的格式,请使用以下正则表达式:

var emailExp = new RegExp(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i);
Run Code Online (Sandbox Code Playgroud)

此正则表达式过滤掉可能输入的任何“垃圾”,并要求使用@符号,点和2-4个字符长的TLD。如果给定电子邮件地址的子字符串与之匹配,则返回该子字符串,否则返回false

您可以使用上面的正则表达式来过滤给定的电子邮件地址,如下所示:

function filter_email (email) {
   var
      /* Define the recommended regular expression. */
      emailExp = new RegExp(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i),

      /* Use 'match' to filter the email address given and cache the result. */
      filtered = email.match(emailExp);

   /* Return the filtered value or false. */
   return filtered ? filtered[0] : false;
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 一年多前回答OP的问题时,我误以为他打算进行电子邮件验证,因为它试图过滤给定的字符串,只保留给它的子字符串,即电子邮件地址。

  • 此答案认为缺少TLD的地址无效,即使按照OP的要求在现实世界中完全有效也是如此。