DateTimeNotLessThanAttribute.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web.Mvc;
  6. using System.ComponentModel.DataAnnotations;
  7. namespace Bowin.Common.Mvc
  8. {
  9. [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
  10. public class DateTimeNotLessThanAttribute : ValidationAttribute, IClientValidatable
  11. {
  12. private const string DefaultErrorMessage = "{0} 不得小于 {1}。";
  13. public DateTimeNotLessThanAttribute(string otherProperty, string otherPropertyName)
  14. : base(DefaultErrorMessage)
  15. {
  16. if (string.IsNullOrEmpty(otherProperty))
  17. {
  18. throw new ArgumentNullException("otherProperty");
  19. }
  20. OtherProperty = otherProperty;
  21. OtherPropertyName = otherPropertyName;
  22. }
  23. public string OtherProperty { get; private set; }
  24. private string OtherPropertyName { get; set; }
  25. public static string FormatPropertyForClientValidation(string property)
  26. {
  27. if (property == null)
  28. {
  29. throw new ArgumentException("属性值不能为空!", "property");
  30. }
  31. return ("*." + property);
  32. }
  33. public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  34. {
  35. var clientValidationRule = new ModelClientValidationRule()
  36. {
  37. ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
  38. ValidationType = "notlessthan"
  39. };
  40. clientValidationRule.ValidationParameters.Add("otherproperty", FormatPropertyForClientValidation(OtherProperty));
  41. return new[] { clientValidationRule };
  42. }
  43. public override string FormatErrorMessage(string name)
  44. {
  45. return string.Format(ErrorMessageString, name, OtherPropertyName);
  46. }
  47. protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  48. {
  49. if (value != null)
  50. {
  51. var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(OtherProperty);
  52. var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
  53. DateTime dtThis = Convert.ToDateTime(value);
  54. DateTime dtOther = Convert.ToDateTime(otherPropertyValue);
  55. if (dtThis < dtOther)
  56. {
  57. return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
  58. }
  59. }
  60. return ValidationResult.Success;
  61. }
  62. }
  63. }