4

这是我的 jQuery 脚本的一部分。我需要让系统验证特定域的电子邮件。

比如example@schooldomain.com

并且只允许来自@schooldomain.com 的电子邮件

代码:

email: function(value,element){return this.optional(element)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);}
4

2 回答 2

9

首先,正如评论中所指出的,使用正则表达式验证电子邮件,然后检查电子邮件是否来自正确的域。

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,}))$/;
    if(re.test(email)){
        //Email valid. Procees to test if it's from the right domain (Second argument is to check that the string ENDS with this domain, and that it doesn't just contain it)
        if(email.indexOf("@thedomain.com", email.length - "@thedomain.com".length) !== -1){
            //VALID
            console.log("VALID");
        }
    }
}
于 2012-08-29T09:52:46.660 回答
0

感谢这个线程,我找到了另一种解决方案,在“at”/“@”之后只接受一个特定域。在 JavaScript 中获取字符串中破折号后的所有内容 基本上将电子邮件一分为二,@ 之前的文本和 @ 之后的文本。如果 @ 之后的文本不等于指定的域,则验证将为 false。

 // Email validation   
let em = document.forms['Login']['email'].value; 
let atpos = em.indexOf("@");
let domain = em.split("@")[1]; // Saves user input after the @ (at)

if (em == null || em == "") {
    alert("Email can not be empty.");
    document.getElementById('e').focus();
    return false;
} 
                                            // First test checks for atleast one character before @
else if (atpos < 1 || domain != "gmail.com"){ // Second test checks if the user entered a gmail.com domain after @
    alert("Not a valid e-mail address. Please write your gmail address like this: username@gmail.com.");
    document.getElementById('e').focus();
    return false;
} 
于 2021-04-15T18:07:33.513 回答