仅验证/接受来自特定域名的电子邮件

时间:2012-08-29 09:47:41

标签: javascript jquery email-validation

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

like 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);}

2 个答案:

答案 0 :(得分:3)

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

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");
        }
    }
}

答案 1 :(得分:0)

多亏了这个线程,我找到了另一种解决方案,在“at”/“@”之后只接受一个特定域。 Get everything after the dash in a string in JavaScript 基本上将电子邮件分为两部分,@ 之前的文本和@ 之后的文本。如果@ 之后的文本不等于指定的域,则验证为假。

 // 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;
}