Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi, I am using MVC on my form and my Model is as follows

C#
 [Required(ErrorMessage = "E-mail must be entered")]
[DataType(DataType.EmailAddress,ErrorMessage="invalid")]
public string UserName { get; set; }


Its is checking validation against Required attribute but not against datatype. Could anyone explain why? Added reference to DataAnnotation.dll, overrided IsValid method of RegularExpressionAttribute class... No results.. huh
Thank you.
Posted
Updated 4-May-21 9:27am
v2

[DataType(DataType.EmailAddress,ErrorMessage="invalid")]

This is not sufficient to set a validation on a field.
For email validation, use regular expressions as validation.

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx[^] is a good example on email validation.
 
Share this answer
 
Comments
[no name] 23-Jan-14 4:38am    
believe me I am doing same for last 2 days, no validation fired yet.
[RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-‌​]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
 
Share this answer
 
Apparently this works:

C#
using System.ComponentModel.DataAnnotations;
    [Required]
    [EmailAddress]
    public String Email { get; set; }
 
Share this answer
 
Comments
[no name] 23-Jan-14 4:21am    
I am unable to use [EmailAddress] in my project
Christian Graus 23-Jan-14 4:26am    
Then you either need to add a reference, use a newer MVC version, or use regex :)
[no name] 23-Jan-14 4:35am    
I have added reference to DataAnnotation, new version not possible as project is older, no regex is working, I already tried 20-25 working regexes :(
Christian Graus 23-Jan-14 4:40am    
Don't try 20-25. They ALL work. Work out why none of them work when you use them wrong.
[no name] 23-Jan-14 4:41am    
I have already made lot of efforts, you can see updated question.
you can try

C#
[EmailAddress]



C#
[DataType(DataType.EmailAddress,ErrorMessage="invalid")] this way not work
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900