How to create a property based on several conditions?

I have a list of switch pairs (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; } public string MedicalExplanation { get; set; }

My goal is to make Explanation necessary if any of the radio buttons is set to true.

My first attempt was to use [Required] , but it does not handle the conditions.

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

Now the problem is that I do not know how to do this if any of Q2, Q3, Q4 is checked.

I ask for advice

+6
source share
2 answers

In your ViewModel, create the bool property as follows:

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

Then use the RequiredIf attribute as follows:

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

UPDATE:

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

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

Here is how I did it:

First, I created a special validation attribute that receives a string array of fields for validation:

 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 as follows (I use resource files to localize 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; } 

This is only the actual error setting on the first checkbox. If you use the built-in css highlighting to highlight fields by mistake, you will need to slightly change this value so that it looks correct, but I felt like it was a clean solution that was reused and allowed me to take advantage of resource file support in validation attributes.

+3
source

Source: https://habr.com/ru/post/950015/


All Articles