Search code examples
c#wpfvalidationmvvmdata-annotations

How to make a field required, based on the value of another field


I have a ViewModel with some public properties that have data annotations, like this:

[Required]
public string PointOfContact { get; set; }

Which works just fine. I've got all of the necessary plumbing in place to display the proper control formatting and error messages when validation fails.

However, I have some fields that are conditionally required based on the value of a checkbox. For example:

public bool Briefing { get; set; }
public DateTime BriefingTime { get; set; }

In this case, I only want BriefingTime to be required if the checkbox that is bound to the Briefing property is checked. The visibility of BriefingTime is already bound to Briefing, so all I need is for it to have the usual Required behavior when the checkbox is checked.

Is there a way to do this out-of-the-box, or do I need to write my own Data Annotation class? What would such a class look like?


Solution

  • You could write your own custom ValidationAttribute:

    public class BriefingTimeRequiredAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var model = (MyModel)validationContext.ObjectInstance;
            if (model.Briefing && !model.BriefingTime.HasValue)
            {
                return new ValidationResult("BriefingTime is required.");
            }
            return ValidationResult.Success;
        }
    }