One out of two fields required in validation

asp.net-mvc, c#, model-view-controller

Solution

All complex validation starts with your view model inheriting from IValidatableObject. You then override Validate and put in your own validation rules.

IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
    if (String.IsNullOrWhiteSpace(FirstName) && String.IsNullOrWhiteSpace(LastName))
    {
        yield return new ValidationResult("A name must be entered.", new string[] { "FirstName", "LastName" });
    }
}

Note that this only ensures server side validation for this rule. If you want it client side, you'll need to write your own JavaScript / jQuery code to deal with the validation.

Problem

I have 2 fields: FirstName LastName And only one of these is required. But if both are omitted, I want both fields to be highlighted. If one of them is filled in then the model is okay and the form should submit. How can this be done?

Original source