How to validate email domains dynamically in Javascript

Viewed 583

How to validate domains dynamically in javascript?

I have requirement where I need to validate domains (dynamically coming from other input) if it is matching the domain which we are getting from the company name selected then say valid. If it's not matching the domain should say like invalid domain.

For ex: if the

  1. company name is XYZ allowed domain is : @xyz.com
  2. company name is abc allowed domain is : @abc.com

so likewise when we change the company name the domain will change according to company selected.

How can we validate these domains dynamically ?

Below have code which will validate when we have one domain. Can someone help to get the domain validation dynamically?

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)){
        
        if(email.indexOf("@gmail.com", email.length - "@gmail.com".length) !== -1){
            console.log("VALID");
        }
    else {
       console.log('INVALID');
    }
  }
}
validateEmail('zk@gmail.com'); //VALID
validateEmail('zk@mail.com'); //INVALID

3 Answers

If you need to match single domain

function validateDomain(email, companyName){ 
  let match = email.match(/^\w+@(\w+).\w+$/);  
  return match!==null &&  match[1]===companyName;
}

validateDomain('gk@gmail.com','gmail') //returns true
validateDomain('gk@gmail.com','email') //returns false
validateDomain('gk.com','gmail') //returns false

If you need to match array of domains

function validateDomain(email, companyNameArr){ 
  let match = email.match(/^\w+@(\w+).\w+$/);  
  return match!==null &&  companyNameArr.includes(match[1]);
}



validateDomain('gk@gmail.com',['gmail','yahoo']) //returns true
validateDomain('gk@gmail.com',['email','yahoo']) //returns false
validateDomain('gk.com',['gmail','yahoo']) //returns false

Why not use string functions instead?

return email.indexOf(domain) < 0

But if you insist with using the Regexp, it would be around like this:

var regex = new RegExp("\\w+@"+domain+"\\.\\w+");
return regex.test(email);

I found the below solution and it works.

function validateDomain(email, companyName){ 
        return companyName.some((val) => email.includes(val))
      }         

     console.log(validateDomain('lk@gmailL.com', ['gmailL.com', 'gmail.com','fa.com']));
Related