Defoncesko
Defoncesko

Reputation: 687

Regex / Pattern HTML email

Is there a way to associate two regex ?

I have this one which prevents user to use this email ([email protected])

pattern="^(([email protected]).)*$"

I also have one which validates email syntax

pattern="[a-z0-9._%+-]{3,}@[a-z]{3,}([.]{1}[a-z]{2,}|[.]{1}[a-z]{2,}[.]{1}[a-z]{2,})"

How to merge those two regex in order to prevent user to user [email protected] and to validate the email syntax ?

I tried to use an OR operator (single pipe) but I am missing something, it doesn't work ...

Thanks !

Upvotes: 1

Views: 1953

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626816

It seems you may use

pattern="(?!test@test\.com$)[a-z0-9._%+-]{3,}@[a-z]{3,}\.[a-z]{2,}(?:\.[a-z]{2,})?"

Note that the HTML5 patterns are automatically anchored as they are wrapped with ^(?: and )$ at the start/end, so no need adding ^ and $ at the start/end of the pattern.

The (?!test@test\.com$) negative lookahead will fail the match if the input string is equal to the [email protected] string (unlike your first regex that only fails the input that contains the email).

The rest is your second pattern, I only removed {1} that are implicit and contracted an alternation group to a \.[a-z]{2,}(?:\.[a-z]{2,})? where (?:\.[a-z]{2,})? is an optional non-capturing group matching 1 or 0 sequences of . and 2 or more lowercase ASCII letters.

Add A-Z to the character classes to also support uppercase ASCII letters.

Upvotes: 1

Related Questions