Keith Grout
Keith Grout

Reputation: 919

Regular expression for multiple emails with ng-pattern

I am attempting to use ng-pattern to filter out most major email addresses.

This is my regular expression, which admittedly I am not very versed in.

<input type="email" name="email" ng-model='email.userInput' 
placeholder="Please enter your work email" 
ng-pattern="/^[A-Z0-9._%+-]+@(yahoo\.com|gmail\.com|msn\.com|hotmail\.com|live\.com)/">

I simply want to fail on the emails listed above... just looking for a step in the right direction.

Upvotes: 0

Views: 1227

Answers (1)

Sam
Sam

Reputation: 20486

Change your alternating group of invalid email domains to a negative lookahead ((?!...)):

^[A-Z0-9._%+-]+@(?!yahoo\.com|gmail\.com|msn\.com|hotmail\.com|live\.com)

Demo


To elaborate, a lookaround is a zero-width assertion meaning it doesn't actually match any characters. Since this is a negative lookahead, as soon as we match the @, we will check to make sure it is not followed by yahoo.com, etc. Because of how this works, we can actually simplify a lot of this (since [A-Z0-9._%+-]+ may not cover a wide range of emails, which `type="email" should validate for us). I would personally use something like this:

@(?!(?:yahoo|gmail|msn|hotmail|live)\.com|$)

This will only match the @ symbol as long as they are not followed by yahoo/gmail/etc, .com and the end of the string.

Upvotes: 2

Related Questions