添加MVC3不显眼的验证(addMinMax)

时间:2011-05-24 14:16:37

标签: jquery asp.net-mvc-3 unobtrusive-validation

我有这样的属性:

public class AgeRangeAttribute:ValidationAttribute,IClientValidatable
    {
public int MinAge { get; set; }

        public int MaxAge { get; set; }

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule
                                                {
                                                    ErrorMessage = ErrorMessage,
                                                    ValidationType = "agerange"
                                                };
            if (MinAge != int.MinValue)
            {
                rule.ValidationParameters.Add("minage", DateTime.Now.AddYears(-MinAge).ToShortDateString());
            }
            if(MaxAge != int.MinValue)
            {
                rule.ValidationParameters.Add("maxage", DateTime.Now.AddYears(-MaxAge).ToShortDateString());
            }
            yield return rule;
        }
}

和JS验证器表示:

jQuery.validator.addMethod("agerangemin", function (value, element, param) {
    var date = setDate(new Date(),value);
    var expected = setDate(new Date(), param);
    return date <= expected;
});

jQuery.validator.addMethod("agerangemax", function (value, element, param) {
    var date = setDate(new Date(), value);
    var expected = setDate(new Date(), param);
    return date > expected;
});

jQuery.validator.addMethod("agerangemaxmin", function (value, element, param) {
    var date = setDate(new Date(), value);
    var expectedMin = setDate(new Date(), param[1]);
    var expectedMax = setDate(new Date(), param[0]);
    return date <= expectedMin && date > expectedMax;
});


jQuery.validator.unobtrusive.adapters.addMinMax("agerange", "agerangemin", "agerangemax", "agerangemaxmin");

并且这个js不起作用(没有例外......可能已经死了&amp; :))

但这很好用:

jQuery.validator.addMethod("agerange", function (value, element, param) {
    var date = new Date();
    date = setDate(date, value);
    var expected = setDate(new Date, param);
    return date <= expected;
});

jQuery.validator.unobtrusive.adapters.addSingleVal("agerange", "minage");

它有什么问题吗?错误在哪里?

1 个答案:

答案 0 :(得分:0)

一年前我在自定义不显眼验证方面遇到了一些困难。这就是我想出的。我需要创建验证器,检查用户是否已满十八岁。

我的代码:

public class CustomEiteenthValidator : ValidationAttribute, IClientValidatable
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null) return null;
            DateTime date = Convert.ToDateTime(value);
            var minDate = DateTime.Now.AddYears(-18);
            if (date > minDate) 
            return new ValidationResult("Employee should be more than 18 years");
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule()
            {
                ValidationType = "eiteenth",
                ErrorMessage = "Employee should be more than 18 years"
            };
            var date = DateTime.Now.AddYears(-18);
            rule.ValidationParameters["date"] = String.Format("{0:dd/MM/yyyy}", date).Replace('.', '/');
            yield return rule;
        }
    }

模特:

        [Required]
        [DataType(DataType.DateTime)]
        [CustomEiteenthValidator]            
        public DateTime Birthday { get; set; }

CustomDateValidation.js中的一些java脚本代码:

 function isFormValid() {
        var valid = true;
        $('.field-validation-error').each(function () {
            valid = false;
        });
        return valid;
    }

(function ($) {
    $.validator.addMethod("eiteenthcheck", function (val, elem, params) {
        if (!val) {
            return false;
        }
        try {
            var birthday = $.datepick.parseDate("dd/mm/yyyy", val);
            var maxBirthday = $.datepick.parseDate("dd/mm/yyyy", $(elem).attr('data-val-eiteenth-date'));
        }
        catch (e) {
            return false;
        }
        if (maxBirthday.getTime() > birthday.getTime()) return true;
        return false;
    });

    $.validator.unobtrusive.adapters.add("eiteenth", ["date"], function (options) {
        options.rules["eiteenthcheck"] = 'eiteenthcheck';
        if (options.message) options.messages["eiteenthcheck"] = options.message;
    });
} (jQuery));

在视图中我渲染文本框:

<%: Html.EditorFor(model => model.Birthday) %>
<%: Html.ValidationMessageFor(model => model.Birthday) %>

最后一个是我使用的脚本:

    <script src="<%= Url.Content("~/Scripts/jquery-1.7.1.min.js") %>" type="text/javascript"></script>   
    <script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/jquery.datepick.js") %>" type="text/javascript"></script>
    <script src="<%= Url.Content("~/Scripts/CustomDateValidation.js") %>" type="text/javascript"></script>