Devilism
Devilism

Reputation: 157

JavaScript regex for email address with a 40 character limit

I am trying to match a regex for an email address with the following conditions.

So Far, I am able to fulfill only the second condition with this regex:

/^[a-z0-9.]+@[a-z0-9.-]+\.[a-zA-Z]{2,6}$/

Any idea, how can I complete the other conditions?

Upvotes: 1

Views: 1816

Answers (2)

The fourth bird
The fourth bird

Reputation: 163457

You can use a single negative lookahead to make sure that the string does not contain 41 characters.

If you repeat the character class without a period 1 or more times, followed by optionally repeating a group that starts with a period, you prevent matching consecutive periods.

This part \.[a-zA-Z]{2,6}$ already makes sure that there is at least a single period.

^(?!.{41})[a-z0-9]+(?:\.[a-z0-9]+)*@[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-zA-Z]{2,6}$

Regex demo

Note that because the - is still in this character class [a-z0-9-]+, consecutive hyphens are still possible. If you don't want to allow this, you can use

^(?!.{41})[a-z0-9]+(?:\.[a-z0-9]+)*@[a-z0-9]+(?:[.-][a-z0-9-]+)*\.[a-zA-Z]{2,6}$

Upvotes: 2

Barney Szabolcs
Barney Szabolcs

Reputation: 12524

Use positive lookahead:

/(?=^[a-z0-9.]+@[a-z0-9.-]+\.[a-zA-Z]{2,6}$)(?=^.{1,40}$)/

reference: https://stackoverflow.com/a/469951/1031191 by Jason Cohen:

"(?=match this expression)(?=match this too)(?=oh, and this)"

tested on: https://regex101.com/

Upvotes: 0

Related Questions