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

前端 未结 2 713
旧巷少年郎
旧巷少年郎 2021-01-02 19:25

I am creating a day range validator using DataAnnotations, jQuery.validate and jquery.validate.unobtrusive. I\'ve already read the following: http://bradwilson.typepad.com/

2条回答
  •  悲哀的现实
    2021-01-02 19:50

    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.

提交回复
热议问题