简体   繁体   English

电子邮件正则表达式验证JavaScript不应包含example.com

[英]Email regex validation javascript should not contain example.com

I have requirement for email validation that the email should not be with a particular domain, 我要求进行电子邮件验证,以确保该电子邮件不应属于特定域,

for example if the email is email@example.com it is invalid. 例如,如果电子邮件为email@example.com ,则该电子邮件无效。 That is the RegExp should exclude the domain example.com 那是RegExp应该排除域example.com

I tried to use like to exclude a string like 我尝试使用like排除类似字符串

^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$.?!example.com

It's not working 没用

Please help me with a RegExp . 请通过RegExp帮助我。

Use this regex 使用此正则表达式

(?=.*@)(?!.*example).*

This matches, all emails, that does not come from domain example.com 这匹配所有不是来自example.com域的电子邮件

I've made a function for you. 我为你做了一个功能。

function isValidEmail(input, excludedDomain) {
    alert(new RegExp("(?=.*@)(?!.*" + excludedDomain + ").*").test(input));
}
isValidEmail("hi@example.com", "example"); //false
isValidEmail("hi@hotmail.com", "example"); //true

Demo: http://jsfiddle.net/W3rLU/ 演示: http//jsfiddle.net/W3rLU/

The correct Regexp is something like this. 正确的Regexp是这样的。

^\w+@(?!example\.com)[a-zA-Z_]+?\.[a-zA-Z]{2,3}$

Debuggex Demo Debuggex演示

It means: after the @, check that is not followed by "example.com" and then check that is followed by a character and a two or three letter domain. 这意味着:@之后,请检查其后没有“ example.com”,然后检查其后是一个字符以及两个或三个字母的域。

I also recommend you to change it a bit to allow domain names with numbers and dashes (eg myname@domain-123.com ) and subdomains ( myname@subdomain.domain.com ) with this expression: 我还建议你改变了一点,以便与数字和连字符(如域名myname@domain-123.com )和子( myname@subdomain.domain.com这个表达式):

^\w+@(?!example\.com)[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,6})$

Debuggex Demo Debuggex演示

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

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