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
Try this
let e = ["example@example.gov", "example@example.com", "example@example.co.id", "example@example.org"]; let d = [".com", ".co.id", ".org"]; let f = x=> d.some(y => new RegExp(`@.*?(${y})`).test(x)); let v = e.filter(x=> f(x)); console.log(v); // show valid emails
Explanation : of regexp: It match the letters after first dot after @
. First we get any characters after @ in non-greedy way by .*?
then we open group (
before first dot \\.
and check that all left characters are domain ${y})
.
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"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.