I have an MVC 4 web application and I need to enter and validate some email addresses, without sending an email to the user's email address.
Currently I am using basic regex email validation with this pattern:
[RegularExpression(@"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z",
ErrorMessage = "Please enter correct email address")]
Although this is validating email addresses, it passes 1@1.1 as a valid email address. For the moment I have a validation that requires symbols @ symbols . symbols where the symbols can be numeric/alphabetic and ._- .
I need more standard email validation for my MVC 4 application. How do I do that?
Don't.
Use a regex for a quick sanity check, something like
.@..
, but almost all langauges / frameworks have better methods for checking an e-mail address. Use that.It is possible to validate an e-mail address with a regex, but it is a long regex. Very long.
And in the end you will be none the wiser. You'll only know that the format is valid, but you still don't know if it's an active e-mail address. The only way to find out, is by sending a confirmation e-mail.
Expanding on Ehsan's Answer....
If you are using .Net framework 4.5 then you can have a simple method to verify email address using
EmailAddressAttribute
Class in code.If you are considering REGEX to verify email address then read:
I Knew How To Validate An Email Address Until I Read The RFC By Phil Haack
It is surprising the question of validating an email address continually comes up on SO!
You can find one often-mentioned practical solution here: How to Find or Validate an Email Address.
Excerpt:
See this answer on SO for a discussion of the merits of the article at the above link. In particular, the comment dated 2012-04-17 reads:
Why not just use the
EmailAttribute
?Regex:
Or you can use just:
You need a regular expression for this. Look here. If you are using .net Framework4.5 then you can also use this. As it is built in .net Framework 4.5. Example