[英]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 : 因此,如果用户输入:
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: 您可以分两步进行:
Check that the email is well formed -> example: https://www.regular-expressions.info/email.html , there are many sources on this subject 检查电子邮件的格式是否正确->例如: https : //www.regular-expressions.info/email.html ,关于此主题有很多资料来源
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.