ASP.NET MVC Conditional validation

There’s a much better way to add conditional validation rules in MVC3; have your model inherit IValidatableObject and implement the Validate method:

public class Person : IValidatableObject
{
    public string Name { get; set; }
    public bool IsSenior { get; set; }
    public Senior Senior { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
        if (IsSenior && string.IsNullOrEmpty(Senior.Description)) 
            yield return new ValidationResult("Description must be supplied.");
    }
}

Read more at Introducing ASP.NET MVC 3 (Preview 1).

Leave a Comment