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.
source share