using System; using System.ComponentModel.DataAnnotations; using System.Reflection; using System.Web.Mvc; namespace WX.CRM.Common.MvcValidation { /// /// 两个时间比较,结束时间不能小于开始时间 /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class DateTimeNotLessAttribute : ValidationAttribute, IClientValidatable { private const string DefaultErrorMessage = "{0}不得小于{1}"; public string OtherDTProperty { get; private set; } private string OtherDTPropertyName { get; set; } public DateTimeNotLessAttribute(string otherDTProperty, string otherDTPropertyNamet) : base(DefaultErrorMessage) { if (string.IsNullOrEmpty(otherDTProperty)) { throw new ArgumentNullException("otherDTProperty"); } OtherDTProperty = otherDTProperty; OtherDTPropertyName = otherDTPropertyNamet; } public override string FormatErrorMessage(string name) { return string.Format(ErrorMessageString, name, OtherDTPropertyName); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { PropertyInfo otherDTProperty = validationContext.ObjectInstance.GetType().GetProperty(OtherDTProperty); object otherDTPropertyValue = otherDTProperty.GetValue(validationContext.ObjectInstance, null); DateTime dtThis = Convert.ToDateTime(value); DateTime dtOther = Convert.ToDateTime(otherDTPropertyValue); if (dtThis < dtOther) { return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } } return ValidationResult.Success; } public System.Collections.Generic.IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { ModelClientValidationRule rule = new ModelClientValidationRule { ValidationType = "notlessthan", ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) }; rule.ValidationParameters.Add("otherproperty", OtherDTProperty); yield return rule; } } }