MVC自定义数据验证(两个时间的比较)

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
ErrorMessage不用说了,就是错误消息;
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的代码@using (Html.BeginForm()){
<div>
    <div>
        @Html.LabelFor(model => model.StartDate):
        @Html.TextBox("StartDate","", new { @class = "njt-datetime-minute-picker Wdate" })&nbsp;
        @Html.ValidationMessageFor(model => model.StartDate)
    </div>
    <div>
        @Html.LabelFor(model => model.EndDate):
        @Html.TextBox("EndDate","", new { @class = "njt-datetime-minute-picker Wdate" })&nbsp;
        @Html.ValidationMessageFor(model => model.EndDate)
    </div>
    <p><input type="submit" value="提交" /></p>
</div>
}




//两个以上字段比较


//前台

$.validator.addMethod("notlessthan", function (value, element, params) {
if (!this.optional(element)) {
var otherProp = $('#' + params[0]).val();

var otherprop1 = $('#' + params[0]).val();

 

return (otherProp.val() < value< otherprop1 );
}
return false;
});

 

 $.validator.unobtrusive.adapters.addSingleVal("notlessthan", "otherproperty"); 换成下面的这一段已数组的形式写入


$.validator.unobtrusive.adapters.add("notlessthan", ["otherproperty", "otherproperty1"], function (options) {
options.rules["notlessthan"] = [options.params["otherproperty"], options.params["otherproperty1"]];
if (options.message) {
options.messages["notlessthan"] = options.message;
}
})


后台多添加一个参数

[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; }

private string OtherProperty1 { get; set; }

public DateTimeNotLessThan(string otherProperty, string otherPropertyName, string otherProperty1)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(otherProperty))
{
throw new ArgumentNullException("otherProperty");
}

OtherProperty = otherProperty;
OtherPropertyName = otherPropertyName;
OtherProperty1 = otherProperty1;
}

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);
var EndDate1 = validationContext.ObjectInstance.GetType().GetProperty(OtherProperty1).GetValue(validationContext.ObjectInstance, null);
DateTime dtThis = Convert.ToDateTime(value);
DateTime dtOther = Convert.ToDateTime(otherPropertyValue);

if ((dtThis < dtOther) && EndDate1 != null)
{
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);
clientValidationRule.ValidationParameters.Add("otherproperty1", OtherProperty1);

return new[] { clientValidationRule };
}
}

//实体类

private const string strErrorNotNull = "*必填项";

[DisplayName("开始时间")]
[Required(ErrorMessage = strErrorNotNull)]
public DateTime StartDate { get; set; }

[DisplayName("结束时间")]
[Required(ErrorMessage = strErrorNotNull)]
[DateTimeNotLessThan("StartDate", "开始时间", "EndDate1")]//这个是自定义的数据验证
public DateTime EndDate { get; set; }

 

public DateTime? EndDate1 { get; set; }


复制代码
 
 
转载地址:http://www.cnblogs.com/zhangliangzlee/archive/2012/07/26/2610071.html





posted @ 2017-09-11 14:39  haifeng_0712  阅读(429)  评论(0编辑  收藏  举报