Taylor Ackley
Taylor Ackley

Reputation: 1437

Regex to test for restricted word in email address not working correctly

I have a regular expression that is giving me some trouble. I want to restrict domains that have a certain word in them, such as 'foobar'. I have a regex to test for a certain domain, such as foobar.com, but I also want to cover:

So far my regex, covers almost everything correctly, except if there are characters before foobar so myfoobar.com would not be caught, but foobarcorp.com would. I have tried a mix of w+ and . and * after the @ sign with no luck finding the right combo. Any ideas? I tried to search around stack overflow, but most of the similar questions cover restricting a certain, already known domain where I am trying to cover domains I don't necessarily know about ahead of time.

Code:

var regex = /\w+@((?!foobar).)*\../i;
ngModel.$setValidity('restrict-email', regex.test(value)); 

Upvotes: 0

Views: 101

Answers (3)

YouneL
YouneL

Reputation: 8361

You can try this:

var regex = /\w+@(\w+\.?)?foobar(\w+)?(\.\w+)+/i;

console.log(regex.test('[email protected]'));
console.log(regex.test('[email protected]'));
console.log(regex.test('[email protected]'));
console.log(regex.test('[email protected]'));
console.log(regex.test('[email protected]'));

Upvotes: 1

zfrisch
zfrisch

Reputation: 8660

\w+@?((?!foobar).)*\.

Just missing an optional parameter ?

To be more specific you can list the domains out yourself like so:

\w+@?((?!foobar).)*\.(com|net|co\.uk)

https://regexr.com/3h68s

But that's obviously a decision you can make based on the security you're looking to offer.

Upvotes: 0

Felipe Freitag Vargas
Felipe Freitag Vargas

Reputation: 61

Maybe something like:

/.*(foobar).*/i

I tested it on RegExr and it matched all the cases you mentioned.

Upvotes: 0

Related Questions