简体   繁体   English

如何通过白名单域名正则表达式验证电子邮件

[英]How to validate email by whitelist domain regex

I want to validate domain by whitelist such as : .com , .co.id, .org, 我想通过白名单来验证域,例如:.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 : 因此,如果用户输入:

  • example@example.gov -> invalid example@example.gov-> 无效
  • example@example.com -> valid example@example.com-> 有效

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 @ . regexp的说明 :它匹配@之后第一个点之后的字母。 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}) . 然后我们打开组(在第一个点\\.之前,并检查所有剩余的字符是否是${y})${y})

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")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM