本文转自:http://www.cnblogs.com/zhangliangzlee/archive/2012/07/26/2610071.html
Model:
public class ModelDateTime { private const string strErrorNotNull = "*必填项"; [DisplayName("开始时间")] [Required(ErrorMessage = strErrorNotNull)] public DateTime StartDate { get; set; } [DisplayName("结束时间")] [Required(ErrorMessage = strErrorNotNull)] [DateTimeNotLessThan("StartDate", "开始时间")]//这个是自定义的数据验证 public DateTime EndDate { get; set; } }
自定义的数据验证类:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class DateTimeNotLessThan : ValidationAttribute, IClientValidatable { private const string DefaultErrorMessage = "{0} 不得小于 {1}."; public string OtherProperty { get; private set; } private string OtherPropertyName { get; set; } public DateTimeNotLessThan(string otherProperty, string otherPropertyName) : base(DefaultErrorMessage) { if (string.IsNullOrEmpty(otherProperty)) { throw new ArgumentNullException("otherProperty"); } OtherProperty = otherProperty; OtherPropertyName = otherPropertyName; } public override string FormatErrorMessage(string name) { return string.Format(ErrorMessageString, name, OtherPropertyName); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(OtherProperty); var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null); DateTime dtThis = Convert.ToDateTime(value); DateTime dtOther = Convert.ToDateTime(otherPropertyValue); if (dtThis<dtOther) { return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); } } return ValidationResult.Success; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules( ModelMetadata metadata, ControllerContext context) { var clientValidationRule = new ModelClientValidationRule() { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "notlessthan"//这里是核心点 }; clientValidationRule.ValidationParameters.Add("otherproperty", OtherProperty); return new[] { clientValidationRule }; } }
Server端验证
自定义Server端的validation属性,需要继承自ValidationAttribute,主要方法就是重载IsValid方法。IsValid的方法有两个;
IsValid(Object value)
IsValid(Object value, ValidationContext validationContext)
第一个是比较常用的方法,即取到当前field的值;第二个比较特殊,它还传送了这个field的上下文,通过这个上下文,可以取到这个class中的其他field,例如:
var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(OtherProperty);
Client验证
Client验证主要是个这个field添加验证规则的名称和传递一系列的参数,然后将这个属性添加到前台的html元素中,结合javascript来进行客户端的验证。要自定义Client端的验证规则,需继承IClientValidatable接口。
实现方法:
public IEnumerable<ModelClientValidationRule> GetClientValidationRules( ModelMetadata metadata, ControllerContext context)
这个方法的返回值是可枚举的 ModelClientValidationRule ;换言之,这是个获取客户端验证规则的接口,自定义验证规则,需要从 ModelClientValidationRule 继承派生类。
ModelClientValidationRule 有3个重要的property:
- ErrorMessage : String
- ValidationParameters : IDictionary<String, Object>
- ValidationType : String
ValidationParameters,是一个hash表,key就是参数的名称,value中存参数的值;
ValidationType,这个东西是和前台的javascript相对应的,.NET MVC3默认用的是jQuery.validation,所以ValidationType的值还需要和其中的验证方法相对应,在自定义验证规则后,还需要在前台添加对应的javascript,将自定义的验证的方法加入了jQuery.validation插件中。
前台的JS代码:
(function ($) { $.validator.addMethod("notlessthan", function (value, element, params) { if (!this.optional(element)) { var otherProp = $('#' + params) return (otherProp.val() < value); } return true; }); $.validator.unobtrusive.adapters.addSingleVal("notlessthan", "otherproperty"); } (jQuery));
Html的代码:
new { @class = "njt-datetime-minute-picker Wdate" }:是我调用的一个日期控件
@using (Html.BeginForm()) { <div> <div> @Html.LabelFor(model => model.StartDate): @Html.TextBox("StartDate","", new { @class = "njt-datetime-minute-picker Wdate" }) @Html.ValidationMessageFor(model => model.StartDate) </div> <div> @Html.LabelFor(model => model.EndDate): @Html.TextBox("EndDate","", new { @class = "njt-datetime-minute-picker Wdate" }) @Html.ValidationMessageFor(model => model.EndDate) </div> <p><input type="submit" value="提交" /></p> </div> }
附上完整的Demo:MVC数据验证(两个日期之间的比较判断).rar