I wrote the following custom validation annotation for my project to confirm that at least one checkbox of a group of checkboxes is checked:
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);
}
}
I then use it like this:
[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; }
The aim was to get the check boxes all validating and keep the validations and their localization contained in the ViewModel. This is working, my only concern is that I expected to find an easy google-paste piece of code for this and did not... Am I missing something easier?
As a secondary question I am attaching this to only one checkbox field, which I think is fine; but is there any unintended consequences of that (other than that any css
error highlighting would only apply to the one checkbox)?
boxes.Any((x) => x == true));
– xDaevax Dec 16 '14 at 16:56