javascriptregex

How to validate email by whitelist domain regex


I want to validate domain by whitelist such as : .com , .co.id, .org,

here i have a regex pattern :

/^[_a-z0-9-]+(\.[_a-z0-9-]+)*(\+[a-z0-9-]+)?@[a-z0-9-]+(\.[a-z0-9-]+)*$/i;

so if the user input :

anyone can help me out ? Thank you


Solution

  • You can proceed in two steps:

    function validateEmail(email) {
       
        //check that the input string is an well formed email 
        var emailFilter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
        if (!emailFilter.test(email)) {
            return false;
        }
    
        //check that the input email is in the whitelist
        var s, domainWhitelist = [".com", "co.id", ".org"];
        for (s of domainWhitelist)
          if(email.endsWith(s))
            return true;
        
        //if we reach this point it means that the email is well formed but not in the whitelist
        return false;
    }
    
    console.log("validate ->" + validateEmail(""));
    console.log("validate abc ->" + validateEmail("abc"));
    console.log("validate example@example.gov ->" + validateEmail("example@example.gov"));
    console.log("validate example@example.com ->" + validateEmail("example@example.com"));