Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
- [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; }
- public class ValidateAtLeastOneCheckedAttribute : ValidationAttribute
- {
- protected override ValidationResult IsValid(object value, ValidationContext validationContext)
- {
- Type type = value.GetType();
- IEnumerable<PropertyInfo> checkBoxeProperties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.PropertyType == typeof (bool));
- foreach (PropertyInfo checkBoxProperty in checkBoxeProperties)
- {
- var isChecked = (bool)checkBoxProperty.GetValue(value);
- if (isChecked)
- {
- return ValidationResult.Success;
- }
- }
- return new ValidationResult(base.ErrorMessageString);
- }
- }
- [ValidateAtLeastOneChecked]
- public class CheckBoxList
- {
- public bool Checkbox1 { get; set; }
- public bool Checkbox2 { get; set; }
- public bool Checkbox3 { get; set; }
- public bool Checkbox4 { get; set; }
- public bool Checkbox5 { get; set; }
- }
- Object propertyValue = type.GetProperty(s).GetValue(instance, null);
- if (bool.Parse(propertyValue.ToString())) {//...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement