jQuery.validator.unobtrusive.adapters.addMinMax round trips, doesn't work in MVC3

六眼飞鱼酱① 提交于 2019-11-30 13:49:44

Solved! I forgot/didn't understand that you have to pass jQuery itself into the function closure. Therefore the custom validator on the client side should look like this:

$(function () {
    jQuery.validator.addMethod('dayRange', function (value, element, param) {
        if (!value) return false;
        var valueDateParts = value.split(param.seperator);
        var minDate = new Date();
        var maxDate = new Date();
        var now = new Date();
        var dateValue = new Date(valueDateParts[2],
                            (valueDateParts[1] - 1),
                             valueDateParts[0],
                             now.getHours(),
                             now.getMinutes(),
                             (now.getSeconds()+5));

        minDate.setDate(minDate.getDate() - parseInt(param.min));
        maxDate.setDate(maxDate.getDate() + parseInt(param.max));

    return dateValue >= minDate && dateValue <= maxDate;
});

    jQuery.validator.unobtrusive.adapters.add('dayrange', ['min', 'max', 'dateseperator'], function (options) {
        var params = {
            min: options.params.min,
            max: options.params.max,
            seperator: options.params.dateseperator
        };

        options.rules['dayRange'] = params;
        if (options.message) {
            options.messages['dayRange'] = options.message;
        }
    });
}(jQuery));

I also change the way I add the adapter to unobtrusive so I can add additional properties. Never send to server-side dev to do a front-end engineers job ;) Hope this helps someone.

zicjin

Reference: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

adapters.addMinMax()'s param is orderby this:

adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute

so you need this:

jQuery.validator.unobtrusive.adapters.addMinMax('dayrange', '', '', 'dayrange','minlength', 'maxlength');

AND,,,

param.min, param.max be sure to undefine. param is an purely array as: ['111','000'].

so you need:

var minDate = now.setDate(now.getDate() - param[0]);
var maxDate = now.setDate(now.getDate() + param[1]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!