Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. public class ValidateAtLeastOneChecked : ValidationAttribute {
  2. public string[] CheckBoxFields {get; set;}
  3. public ValidateAtLeastOneChecked(string[] checkBoxFields) {
  4. CheckBoxFields = checkBoxFields;
  5. }
  6.  
  7. protected override ValidationResult IsValid(Object value, ValidationContext context) {
  8. Object instance = context.ObjectInstance;
  9. Type type = instance.GetType();
  10.  
  11. foreach(string s in CheckBoxFields) {
  12. Object propertyValue = type.GetProperty(s).GetValue(instance, null);
  13. if (bool.Parse(propertyValue.ToString())) {
  14. return ValidationResult.Success;
  15. }
  16. }
  17. return new ValidationResult(base.ErrorMessageString);
  18. }
  19. }
  20.  
  21. [ValidateAtLeastOneChecked(new string[] { "Checkbox1", "Checkbox2", "Checkbox3", "Checkbox4" }, ErrorMessageResourceType=typeof(ErrorMessageResources),ErrorMessageResourceName="SelectAtLeastOneTopic")]
  22. public bool Checkbox1{ get; set; }
  23. public bool Checkbox2{ get; set; }
  24. public bool Checkbox3{ get; set; }
  25. public bool Checkbox4{ get; set; }
  26.  
  27. public class ValidateAtLeastOneCheckedAttribute : ValidationAttribute
  28. {
  29. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  30. {
  31. Type type = value.GetType();
  32. IEnumerable<PropertyInfo> checkBoxeProperties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.PropertyType == typeof (bool));
  33.  
  34. foreach (PropertyInfo checkBoxProperty in checkBoxeProperties)
  35. {
  36. var isChecked = (bool)checkBoxProperty.GetValue(value);
  37. if (isChecked)
  38. {
  39. return ValidationResult.Success;
  40. }
  41. }
  42.  
  43. return new ValidationResult(base.ErrorMessageString);
  44. }
  45. }
  46.  
  47. [ValidateAtLeastOneChecked]
  48. public class CheckBoxList
  49. {
  50. public bool Checkbox1 { get; set; }
  51. public bool Checkbox2 { get; set; }
  52. public bool Checkbox3 { get; set; }
  53. public bool Checkbox4 { get; set; }
  54. public bool Checkbox5 { get; set; }
  55. }
  56.  
  57. Object propertyValue = type.GetProperty(s).GetValue(instance, null);
  58. if (bool.Parse(propertyValue.ToString())) {//...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement