How to make a property required based on multiple condition?

假如想象 提交于 2019-12-04 05:33:40

In your ViewModel, create a bool propery like this:

public bool IsMedicalExplanationRequired
{
   get
   {
       return Q1 || Q2 || Q3 || Q4;
   }
}

Then, use your RequiredIf attribute like this:

[RequiredIf("IsMedicalExplanationRequired", true, ErrorMessage = "You must explain any \"Yes\" answers!")]

UPDATE:

If your Q1 - Q4 properties are of type bool?, just change the IsMedicalExplanationRequired property like below:

public bool IsMedicalExplanationRequired
{
   get
   {
       return Q1.GetValueOrDefault() || Q2.GetValueOrDefault() || Q3.GetValueOrDefault() || Q4.GetValueOrDefault();
   }
}

This is how I did it:

First I created a custom validation attribute which gets a string array of fields to check passed in:

public class ValidateAtLeastOneChecked : ValidationAttribute {
    public string[] CheckBoxFields {get; set;}
    public ValidateAtLeastOneChecked(string[] checkBoxFields) {
        CheckBoxFields = checkBoxFields;
    }

    protected override ValidationResult IsValid(Object value, ValidationContext context) {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();

        foreach(string s in CheckBoxFields) {
            Object propertyValue = type.GetProperty(s).GetValue(instance, null);
            if (bool.Parse(propertyValue.ToString())) {
                return ValidationResult.Success;
            }
        }
        return new ValidationResult(base.ErrorMessageString);
    }
}

Then I use it like this (I am using resource files to localize my error messages):

[ValidateAtLeastOneChecked(new string[] { "Checkbox1", "Checkbox2", "Checkbox3", "Checkbox4" }, ErrorMessageResourceType=typeof(ErrorMessageResources),ErrorMessageResourceName="SelectAtLeastOneTopic")]
public bool Checkbox1{ get; set; }
public bool Checkbox2{ get; set; }
public bool Checkbox3{ get; set; }
public bool Checkbox4{ get; set; }

It is only actually setting the error on the first checkbox. If you are using the built in css highlighting to highlight fields in error you will need to modify this slightly to make it look right, but I felt this was a clean solution which was reusable and allowed me to take advantage of the support for resource files in validation attributes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!