S.Shebani
S.Shebani

Reputation: 11

Email validation doesn't work

I have this simple regular expression for Emails.

/^[a-z]+([\.-_]?[a-z0-9]+)*@([a-z]{3,})+(\.[a-z]{2,3})+$/i;

But when I use this example: first@[email protected] it's still works, And Also when I remove @ character from expression :

`/^[a-z]+([\.-_]?[a-z0-9]+)*([a-z]{3,})+(\.[a-z]{2,3})+$/i

it gives the same result.

This expression allows an infinite number of at signs (i.e. @) between at least 2 characters in the email !!

Where is the problem with this expression?

Upvotes: 0

Views: 390

Answers (2)

laser
laser

Reputation: 570

You want something like that?

/^[a-z\.\-_]+@([a-z]{3,})+(\.[a-z]{2,3})+$/

Probably with sign \.-_ you wanted to have either ".", or "-" or "_" to be used inside the regex, but you forgot to escape "minus".

Or you can use your own but with escape:

^[a-z]+([\.\-_]?[a-z0-9]+)*@([a-z]{3,})+(\.[a-z]{2,3})+$

PS: Remember that a real valid email address could be completely different and has a huge regex, and moreover, each web server defines what is allowed and what is not in email.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

Your pattern is rather restrictive, you might think of other options of validating an email address, like type="email" if it is an input field validation.

As to why the regex matches @ even if you take it out, or matches a string with two @ symbols, that is cased by [.-_] that matches a lot of chars as the hyphen creates a range that includes @. You need to use [._-] instead.

enter image description here

You may "fix" the regex as

/^[a-z]+([._-]?[a-z0-9]+)*[a-z]{3,}(\.[a-z]{2,3})+$/i

However, this regex is not good to use in real life scenarios.

Upvotes: 3

Related Questions