ValidateExtension.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.Web.Mvc;
  7. using System.Globalization;
  8. using Bowin.Common.JSON;
  9. namespace EMIS.ViewModel
  10. {
  11. public class TotalLengthAttribute : ValidationAttribute, IClientValidatable
  12. {
  13. public int Length { get; set; }
  14. public IList<string> RelateControls { get; set; }
  15. public TotalLengthAttribute(int length, params string[] relateControls)
  16. {
  17. this.Length = length;
  18. if (relateControls == null)
  19. {
  20. RelateControls = new List<string>();
  21. }
  22. else
  23. {
  24. RelateControls = relateControls.ToList();
  25. }
  26. }
  27. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  28. {
  29. string totalString = "";
  30. List<string> errorMessage = new List<string>();
  31. foreach (var relateControl in RelateControls)
  32. {
  33. var property = validationContext.ObjectType.GetProperty(relateControl);
  34. if (property == null)
  35. {
  36. errorMessage.Add(string.Format(CultureInfo.CurrentCulture, "{0} 不存在", relateControl));
  37. continue;
  38. }
  39. //获取属性的值
  40. var otherValue = property.GetValue(validationContext.ObjectInstance, null);
  41. totalString += Convert.ToString(otherValue);
  42. }
  43. if (errorMessage.Count > 0)
  44. {
  45. return new ValidationResult(string.Join(",", errorMessage));
  46. }
  47. if (totalString.Length != this.Length)
  48. {
  49. return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
  50. }
  51. return null;
  52. }
  53. public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  54. {
  55. var rule = new ModelClientValidationRule
  56. {
  57. ValidationType = "totallength",
  58. ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
  59. };
  60. rule.ValidationParameters["length"] = Length;
  61. rule.ValidationParameters["other"] = RelateControls.ToJson();
  62. yield return rule;
  63. }
  64. }
  65. }