jQuery 表单验证,仅允许 .EDU 和 .edu.nn(其中 nn 是 2 位国家/地区代码)电子邮件地址

jQuery Form Validation, Only Allow .EDU AND .edu.nn (where nn is a 2-digit country code) Email Addresses

本文关键字:nn 国家 地区 电子邮件地址 代码 其中 验证 EDU jQuery edu 表单      更新时间:2023-09-26

我使用此方法进行了.edu电子邮件验证 - jQuery表单验证,仅允许.EDU电子邮件地址

但是,不仅仅是 .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
        },
    }
});    

由于.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");

这是另一个测试您的RegExp的网站:http://regexpal.com/

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

x? :表示匹配 0 次或更多次x(有效x是可选的)

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

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

希望它有帮助

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

/.''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
},
    }
});