Email validation Javascript+RegEx, but to exclude certain domains

梦想的初衷 提交于 2021-02-15 07:52:21

问题


I have client side email validation script Javascript+RegEx, it works fine, but I want to exclude certain domains while validating, namely all Apple domains since they do not work (emails sent to these addresses are deleted without any notice): @apple.com, @me.com, @icloud.com, @mac.com.

I found appropriate questions here, but still they are not the same I am asking for help. Please, help to implement this

Can it be done via RegEx modification, or I have to use loop and search substrings (@apple.com, @me.com, @icloud.com, @mac.com) after the main email validation is done?

function verifyMe(){
var msg='';

var email=document.getElementById('email').value;
if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) || 
document.getElementById('email').value=='')
{
msg+='- Invalid Email Address: '+email+'\n\n';
document.getElementById('Eemail').style.color='#ffffff';
}
else
document.getElementById('Eemail').style.color='#bbb'
 
if(msg!='')
return false; 
else
{
search_code(); //it's ok go ahead
return true;
}
}

回答1:


Both approaches would work.

For the regex one, just insert the following part after the @ in the regex (negative lookahead):

(?!(?:apple|me|icloud|mac)\.com$)

But a better regex overall would be:

^\w+[-\.\w]*@(?!(?:apple|me|icloud|mac)\.com$)\w+[-\.\w]*?\.\w{2,4}$

For the other approach, the following should work:

function isValidMailAddress(email) {
    var match = /^\w+[-\.\w]*@(\w+[-\.\w]*?\.\w{2,4})$/.exec(email);
    if (!match)
        return false;

    var forbiddenDomains = ["apple.com", "me.com", "icloud.com", "mac.com"];
    if (forbiddenDomains.indexOf(match[1].toLowerCase()) >= 0)
        return false;

    return true;
}

It's up to you to decide which approach you feel most comfortable with.




回答2:


You can use jQuery.inArray() for checking email with a specific domain name.

var email ="abc@xyz.edu.au" 
var str = email.split('@').slice(1);
var allowedDomains = ['xyz.edu.au','abc.edu.au'];

if($.inArray(str[0], allowedDomains) === -1) {
   alert('email is allowed.');
}
else{
   alert('email not allowed.');
}


来源:https://stackoverflow.com/questions/26388648/email-validation-javascriptregex-but-to-exclude-certain-domains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!