Using [RegularExpression(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$")] attribute never validates an email property of my model. I'm new to regular expressions so I can't figure out what is the problem. Little help?
Asked
Active
Viewed 1.0k times
2
Rade Milovic
- 875
- 4
- 13
- 29
-
Could you provide an input that should match the regex? Are the emails *contained* in strings? For example, either `x@x.x` or `text before x@x.x text after`? – sp00m Mar 25 '13 at 11:06
-
For example johndoe@gmail.com or john.doe@gmail.com should pass. – Rade Milovic Mar 26 '13 at 14:34
-
[MVC Email Regular Expression C#](http://lesson8.blogspot.com/2013/03/email-regular-expression-mvc-c.html) – Sender Oct 03 '13 at 16:59
3 Answers
9
[Required]
[Display(Name = "Email Address")]
[EmailAddress]
public string email { get; set; }
Something like this should solve you problem. The email validation has been build in 4.5 check out this msdn documentation
Just another Steve
- 136
- 1
- 3
-
1This approach doesn't work with older browsers (which doesn't support input type of email). So you should provide RegularExpression attribute as a fallback. – Rade Milovic Jul 29 '13 at 16:36
1
Did you check the ModelState property for validation errors? Look at the example at the bottom of this page:
http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
for a way of sending back error messages to the client when validation fails.
Youssef Moussaoui
- 11,874
- 2
- 39
- 35
-
Yes I have done that part. The problem is that email is never validated, even when it's in a correct form. This regex should validate johndoe@gmail.com, but it doesn't. – Rade Milovic Mar 25 '13 at 10:57
-
I can't reproduce your issue. If I try to send johndoe, I get "The field Email must match the regular expression '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$'." as a model state error. So it looks like it's validating just fine. – Youssef Moussaoui Mar 25 '13 at 12:28
1
Look at this article: How To Validate Email Address With Regular Expression. The guy not only providing you with the regular expression, but also explaining step by step what it means. Not only its useful as an expression, but you can also learn a thing or two from this article.
Hope this helps. Please let me know if not.
Display Name
- 4,714
- 1
- 31
- 43