Assuming your class currently looks something like this:
[ValidateThisForm]
public class MyViewModel
{
public bool TestOne { get; set; }
public bool TestTwo { get; set; }
}
If you have complex model-level validation you want to perform, where you can't simply annotate a single property, you can hook into the validation pipeline with IValidatableObject
like this:
public class MyViewModel : IValidatableObject
{
public bool TestOne { get; set; }
public bool TestTwo { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (TestOne == false && TestTwo == false)
{
yield return new ValidationResult("Form Incomplete: Please correct")
}
}
}
You can continue to yield return
as many validation messages as you'd like. And you can display them all on the client with @Html.ValidationSummary
If you'd like the message to appear alongside a particular control, the ValidationResult
constructor takes an overload with the memberNames
of the affected properties so you could change the Validate
method like this:
if (TestOne == false && TestTwo == false)
{
yield return new ValidationResult("Form Incomplete Message", new[] {"TestOne"})
}
Then you can provide the validation message for that particular property with the ValidationMessageFor
HTML helper like this:
@Html.ValidationMessageFor(Function(model) model.TestOne )
For further reading, Scott Guthrie wrote about using IValidatableObject
as part of his blog post introducing new features in MVC3 and had a follow up post with more detail on class level validation shortly thereafter.