How can I validate a complex model using ASP.NET MVC 2
public class UserModel { [Required(ErrorMessage = "Le nom est requis.")] [UIHint("String")] [DataType(DataType.Text)] [DisplayName("Nom")] public string Lastname { get; set; }
[DataType(DataType.Text)]
[UIHint("String")]
[DisplayName("Prénom")]
public string Firstname { get; set; }
[Required(ErrorMessage="La spécialité principale est requise.")]
[DisplayName("Spécialité principale")]
public Speciality PrimarySpeciality { get; set; }
[DisplayName("Spécialité secondaire")]
public Speciality SecondarySpeciality { get; set; }
}
public class SpecialityModel
{
[Required(ErrorMessage = "La spécialité est requise.")]
public int Id { get; set; }
public string Name { get; set; }
}
How can the primary Speciality be required and not the second one? It seems that the Required attribute only check for nullable but Speciality is never null.
Edit:
After reading this post http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html i'm reformulating my question :How can i prevent sub properties validation to occur before main object. As you can see the SecondarySpeciality is not Required but still get validated cause of the DataAnnotation on the Address class. I'm thinking that mvc2 cannot work with model validation. Should i just go with plain model ? (which means a lot more mapping but if it's work...)
To do validation on complex objects you need to implement custom validation by creating your own validation attribute. I would type out a quick example but Phil Haack has a great article on this at:
http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
Write your own validator in which you can use Enum.IsDefined
method to determine if the value of Speciality is set correctly.
You just need to create class RequiredEnumAttribute
that will derive from ValidationAttribute
and overrides IsValid
method.
Example is avaible here.
链接地址: http://www.djcxy.com/p/56604.html上一篇: 验证多个属性