pdace
pdace

Reputation: 35

Regex - Validate that the local part of the email is not ending with a dot while only allowing certain characters without using a lookbehind

I was using a lookbehind to check for a dot before the @ but just realized not all browsers are supporting lookbehinds. It works perfect in Chrome but fails in Firefox and IE.

This is what I came up with but it certainly is messy

^([a-zA-Z0-9&^*%#~{}=+?`_-]\.?)*[a-zA-Z0-9&^*%#~{}=+?`_-]@([a-zA-Z0-9]+\.)+[a-zA-Z]$

Is there a simpler and/or more elegant way to do this? I don't think I can negate the dot (^.) because I'm only allowing certain characters to be present in the local part.

Upvotes: 1

Views: 321

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627488

This ([a-zA-Z0-9&^*%#~{}=+?`_-].?)*[a-zA-Z0-9&^*%#~{}=+?`_-] part is not messy, but inefficient, because the * quantifies a group containing an obligatory part, [...], and an optional \.?. Instead of (ab?)*a, you may use a+(?:ba+)* that will make matching linear and swift, in your case, [a-zA-Z0-9&^*%#~{}=+?`_-]+(?:.[a-zA-Z0-9&^*%#~{}=+?`_-]+)*.

More, [a-zA-Z0-9_] equals \w in JS regex, you may use this to shorten the pattern.

Besides, the last [a-zA-Z]$ pattern only matches a single letter, you most probably need [a-zA-Z]{2}$ there, as TLDs consist of 2+ letters.

So, you may use

^[\w&^*%#~{}=+?`-]+(?:\.[\w&^*%#~{}=+?`-]+)*@(?:[a-zA-Z0-9]+\.)+[a-zA-Z]{2,}$

See the regex demo.

Upvotes: 1

Related Questions