I am validating a class with DataAnnotations utils.
I have a class that has a Title
property and an Item
property.
I want to apply a Requir
well, on property level contingent validations are hard to achieve in MVC. but u can extend the framework or u can use some other library to achieve the goal. i m using foolproof validation by nick successfully for contingent validations in my project. u can take a look at it here
You may be able to do this by creating a custom validation attribute for the class. Unfortunately DataAnnotation attributes assigned to properties cannot access other properties of the parent class as far as I am aware hence the need to create a class validator.
Using the System.ComponentModel.DataAnnotations namespace you will need to create you custom attribute class inheriting from ValidationAttribute and override the IsValid method (I have not tested the code below but it should get you going):
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
sealed public class CustomAttribute: ValidationAttribute
{
public CustomAttribute()
{
}
public override bool IsValid(object value)
{
if(value is myClass)
{
return ((myClass)value).Item != null &&
string.IsNullOrEmpty(((myClass)value).Title) ? false : true;
}
else return true;
}
}
Digging a little further it appears that whilst cross field validation it not possible out of the box it can be achieved by extending the framework to support it. See this article for details, hopefully this will be added to future versions of MVC.