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

前端 未结 2 687
旧巷少年郎
旧巷少年郎 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:31

    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]);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题