【问题标题】:jQuery Form Validation, Only Allow .EDU AND .edu.nn (where nn is a 2-digit country code) Email AddressesjQuery 表单验证,仅允许 .EDU 和 .edu.nn(其中 n 是 2 位国家代码)电子邮件地址
【发布时间】:2015-01-06 21:22:49
【问题描述】:

我使用这种方法进行了 .edu 电子邮件验证 - jQuery Form Validation, Only Allow .EDU Email Addresses

但我想将两者合二为一,而不只是 .edu 或 .edu.nn(其中 nn 是 2 位国家代码)。无法弄清楚如何实现这一目标。 下面是同时接受 .edu 和 .edu.fr 的代码 - 除了 .edu 之外,我还需要接受所有其他 2 位国家代码

感谢您的帮助!

$.validator.addMethod("edu", function (value, element, param) {
// Make it work optionally OR
//  Check the last 4 and 7 characters and ensure they match .edu and .edu.2-digit-country-code
return (this.optional(element) || value.slice(-4) == ".edu" || value.slice(-7) ==  ".edu.fr");
}, "Please enter valid .edu email address");

$("#requestform").validate({
    rules: {
        email: {
            required: true,
            email: true,
            edu: true
        },
    }
});    

【问题讨论】:

  • 您是否打算拥有一组有效的国家代码?如果不只是删除最后一个条件,或者更改它以检查最后 2 个字符是否仅为字母

标签: javascript jquery jquery-validate


【解决方案1】:

由于.slice() 的性能不如同时检查两种可能性,因此使用带有可选标志的 RegExp 会更快:

这个正则表达式将匹配两个条件:

var regex = /\.edu(\.[a-z]{2})?$/

在这里查看它在 REPL 中的工作:

> regex.test('somename.edu')
true
> regex.test('emai.com')
false
> regex.test('email.edu.cz')
true

那么你的验证器函数会像这样小:

$.validator.addMethod("edu", function (value, element, param) {
    // Make it work optionally OR
    //  Check the last 4 and 7 characters and ensure they match .edu and .edu.2-digit-country-code
    return (value.match(/\.edu(\.[a-z]{2})?$/));
}, "Please enter valid .edu (or .edu.NN) email address");

这里是另一个网站来测试你的RegExphttp://regexpal.com/

另外,这里是我使用的 RegExp 语法的一些解释:

x?:表示匹配x 0 次或多次(实际上x 是可选的)

x{N}: 表示匹配x 精确N 次(用于精​​确匹配2 个字母a-z)

$: 表示匹配“输入结束”(否则someacct.edu.fr@gmail.com 也会匹配)

希望对你有帮助

【讨论】:

    【解决方案2】:

    改用正则表达式匹配。 Here 是一个很棒的工具。

    /.\edu.[a-z][a-z]/i

    $.validator.addMethod("edu", function (value, element, param) {
    // Make it work optionally OR
    //  Check the last 4 and 7 characters and ensure they match .edu and .edu.2-digit-country-code
    return (this.optional(element) || value.slice(-4).match(/\.edu/i) || value.slice(-7).match(/\.edu\.[a-z][a-z]/i);
    }, "Please enter valid .edu email address");
    
    $("#requestform").validate({
    rules: {
        email: {
    required: true,
    email: true,
    edu: true
    },
    
        }
    }); 
    

    【讨论】:

      猜你喜欢
      • 2012-01-30
      • 2010-10-11
      • 2011-01-31
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多