ValidateExtension.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. /// <summary>
  16. ///
  17. /// </summary>
  18. /// <param name="length"></param>
  19. /// <param name="relateControls"></param>
  20. public TotalLengthAttribute(int length, params string[] relateControls)
  21. {
  22. this.Length = length;
  23. if (relateControls == null)
  24. {
  25. RelateControls = new List<string>();
  26. }
  27. else
  28. {
  29. RelateControls = relateControls.ToList();
  30. }
  31. }
  32. /// <summary>
  33. ///
  34. /// </summary>
  35. /// <param name="value"></param>
  36. /// <param name="validationContext"></param>
  37. /// <returns></returns>
  38. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  39. {
  40. string totalString = "";
  41. List<string> errorMessage = new List<string>();
  42. foreach (var relateControl in RelateControls)
  43. {
  44. var property = validationContext.ObjectType.GetProperty(relateControl);
  45. if (property == null)
  46. {
  47. errorMessage.Add(string.Format(CultureInfo.CurrentCulture, "{0} 不存在", relateControl));
  48. continue;
  49. }
  50. //获取属性的值
  51. var otherValue = property.GetValue(validationContext.ObjectInstance, null);
  52. totalString += Convert.ToString(otherValue);
  53. }
  54. if (errorMessage.Count > 0)
  55. {
  56. return new ValidationResult(string.Join(",", errorMessage));
  57. }
  58. if (totalString.Length != this.Length)
  59. {
  60. return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
  61. }
  62. return null;
  63. }
  64. /// <summary>
  65. ///
  66. /// </summary>
  67. /// <param name="metadata"></param>
  68. /// <param name="context"></param>
  69. /// <returns></returns>
  70. public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  71. {
  72. var rule = new ModelClientValidationRule
  73. {
  74. ValidationType = "totallength",
  75. ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
  76. };
  77. rule.ValidationParameters["length"] = Length;
  78. rule.ValidationParameters["other"] = RelateControls.ToJson();
  79. yield return rule;
  80. }
  81. }
  82. }