In my website, I am using the below regex to validate email.
^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$
My doubts are:
Can I use the below regex for the same functionality?
^[a-zA-Z0-9_.-]+@[a-zA-Z0-9.-]+.[a-z]{2,4}$
The reason why I ask this is, I tried to study the meaning. So I got a confusion that
[a-zA-Z0-9_.-]
cover all the instances by [a-zA-Z0-9]
and [a-zA-Z0-9_-]
I a not sure about this, as I am a beginner.
I got the regex from
I checked both regex in http://regex101.com/#pcre. And I can't find any difference in result. May be it is because of my limited knowledge
Please give a clarification. Thanks to all in advance
Maybe it's not the answer you were looking for, but I have to say that I ended up with this kind of email validation: ^.+@.+\..{2,}$
after trimming it.
What does it check? Existence of some symbols, @ itself, some other symbols, dot, and at least two symbols for top-level domain. It says "Dude, there should be an email, not your hilarious username". And that's enough, I guess.
By the way, .[a-z]{2,4}$
is a huge mistake for checking TLD, since there are few popular domains that are longer than 4 symbols (i.e., .travel
) and a lot of less popular ones.
Why do I think that you don't need a detailed validation? First of all, there are a lot of requirements which you'll miss anyway. Do you know that cyrillic symbols are allowed in the email address?
And, please, think what do you want from this validation? Avoid incorrect emails? You won't. Somebody will enter an email, which meet all of your requirements, but it'll be incorrect anyway. Is email@gmial.com
a good one? No. Will it be checked by regexp? I'm afraid, the answer is "no" once again.
So, it's better to explain that user should provide valid email to get confirmation mail and to make an explanation "if you aren't the one, who registered at mysite.com, please just ignore this letter" in the email text.
Because regexp will never filter enough, but you can lose a couple of users with strange email adresses because of it.
And since this should be an answer for your question:
4
from it. If you need the logic of the original one, you can't make it shorter..mail@mail.com
, a@gmail.com
, gmail@a.com