Search code examples
javascriptregexvalidation

Fix Regular Expression for Emails to Not allow Consecutive Periods


my regular Expressions are pretty bad so I thought would look for some help on this.

I have a regular expression:

/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;

and it works for most cases of my email validation however it allows this one through:

test..testing@gmail.com

How would I alter the above Regular Expression to not allow consecutive periods anywhere throughout the string?

Thanks.


Solution

  • To avoid matching two consecutive dots you can add a negative lookahead at the beginning of your regular expression:

    /^(?!.*\.{2})[a-z0-9etc...
     ------------
    

    It will fail to match if there are two consecutive periods anywhere in the string and it doesn't require any other modifications to your original regular expression.

    However it seems a bad idea as your regular expression isn't correct in the first place. If you insist on using regular expressions to validate email addresses, try this: