[英]jQuery Form Validation, Only Allow .EDU AND .edu.nn (where nn is a 2-digit country code) Email Addresses
我使用此方法進行了.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(\\.[az]{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?
:表示匹配x
0次或多次(實際上x
是可選的)
x{N}
意味着匹配x
恰好N
倍(用於匹配正好2字母az)
$
:表示匹配“輸入結束”(否則someacct.edu.fr@gmail.com
也將匹配)
希望能有所幫助
請改用正則表達式匹配。 這是一個很棒的工具。
/.\\edu.[az][az]/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
},
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.