MVC3中的客户端验证无法正常工作

时间:2012-04-25 07:17:03

标签: asp.net-mvc-3 custom-attributes client-side-validation

下面是代码以某种方式客户端验证不起作用...我在这个论坛中搜索了几个问题并写了这个..

这是自定义验证属性“startDateAttribute”

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class StartDateAttribute : ValidationAttribute, IClientValidatable
    {
        public StartDateAttribute ()
        {
        }

        public override bool IsValid(object value)
        {   
            var date = (DateTime)value;
            if (date.Date >= DateTime.Now.Date)
            {
                return true;
            }
            return false;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "DateRange"
            };
        }
    }

    [CurrentDateAttribute(ErrorMessage = "select the correct date")]    
    public DateTime? StartDate { get; set; }

这里添加了JQuery代码

      jQuery.validator.addMethod('DateRange', function (value, element, params) {
     var d = new Date();         
     var currentDate = (d.getMonth()+1)  + "/"+d.getDate()+ "/" + d.getFullYear() ;
    return value >= currentDate;
});

// and an unobtrusive adapter
jQuery.validator.unobtrusive.adapters.add('DateRange', { }, function (options) {
    options.rules['DateRange'] = true;
    options.messages['DateRange'] = options.message;
});

1 个答案:

答案 0 :(得分:0)

客户端验证的一个要求是ValidationType和适配器名称应该匹配,并且应该是小写。

将ValidationType和适配器名称更改为“daterange”并检查