正文转自:http://www.cnblogs.com/zhangliangzlee/archive/2012/07/26/2610071.html

var otherProperty = validationContext.ObjectInstance.GetType().GetProperty(OtherProperty);

Client验证

Client验证主假使个这些田野先生添加验证规则的称呼和传递一层层的参数,然后将以此天性添加到前台的html成分中,结合javascript来展开客户端的辨证。
要自定义Client端的申明规则,需三番五次IClientValidatable接口。
福寿双全情势:
publicIEnumerable<ModelClientValidationRule>GetClientValidationRules(ModelMetadata
metadata,
ControllerContext 
context)
其一艺术的重回值是可枚举的ModelClientValidationRule;换言之,那是个得到客户端验证规则的接口,自定义表达规则,供给从ModelClientValidationRule继承派生类。
ModelClientValidationRule有贰个重大的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代码:

图片 1😉

(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));

图片 2😉

Html的代码:

new { @class = "njt-datetime-minute-picker Wdate" }:是我调用的一个日期控件

图片 3😉

@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>
}

图片 4😉

 

沾满完整的德姆o:MVC数看新闻申明(四个日子之间的相比较判断).rar

 

图片 5😉

图片 6😉

Model:

自定义的数额验证类:

Server端验证

自定义Server端的validation属性,要求继续自ValidationAttribute,首要方式就是重载IsValid方法。

IsValid的办法有四个;
IsValid(Object
value)
IsValid(Object
value, ValidationContext validationContext)

第贰个是相比较常用的章程,即取到当下田野(field)的值;第三个相比新鲜,它还传递了那么些田野的上下文,通过那几个上下文,能够取到那么些class中的其余田野同志,例如:

图片 7

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

图片 8😉

图片 9

图片 10😉

相关文章

网站地图xml地图