How to make a property required based on multiple condition?

meda picture meda · Jul 22, 2013 · Viewed 8.2k times · Source

I have a list of Pair of radio buttons (Yes/No):

Q1.(Y)(N) 
Q2.(Y)(N) 
Q3.(Y)(N) 
Q4.(Y)(N)

and I have one property in my model public string MedicalExplanation { get; set; }

My goal is to make Explanation required if any of the radio button has been set to true.

My first try was to use [Required] but it does not handle conditions.

Then I decided to use third party tool like MVC Foolproof Validation I used it like this: [RequiredIf("Q1", true, ErrorMessage = "You must explain any \"Yes\" answers!")]

Now the problem is I don't know how to make it required if any of the other Q2, Q3, Q4 is checked.

Please advice

Answer

ataravati picture ataravati · Jul 22, 2013

In your ViewModel, create a bool property 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();
   }
}