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
You can proceed in two steps:
Check that the email is well formed -> example: https://www.regular-expressions.info/email.html, there are many sources on this subject
Validate that the domain is in the whitelist of domains
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"));