jQuery Validation conditional rule makes input never valid - valid always returns 0

会有一股神秘感。 提交于 2019-12-23 04:27:04

问题


I'm having a problem with jQuery validation conditional rules.

I specify a conditional rule for an element as such:

var validatorSettings = $("form").data('validator').settings; 
validatorSettings.rules = $.extend({}, validatorSettings.rules, {
        TimeFrameAmount: {
            number: function() { return $("select[name='TimeFrameUnits']").val() === "true"; },
            required: function() { return $("select[name='TimeFrameUnits']").val() === "true" } ;
        }
});

Problem is when I submit the form, $("form").valid() returns 0.

I traced is down to see that $("input[name='TimeFrameAmount']").valid() is the only element in the form that returns 0 and thus is the element causing the form to fail validation.

I further traced this down that $("input[name='TimeFrameAmount']").valid() always returns 0 and causes the form to fail validation even if the conditional rule functions both return false.

I checked this by setting a break point in the conditional rule functions, then triggered a call to $("input[name='TimeFrameAmount']").valid() from the Firefox console.

My conditional rules both return false and $("input[name='TimeFrameAmount']").valid() still returns 0 and the form fails validation.

One thing to note is that the errorPlacement callback in not fired when my conditional rules return false, which makes sense since no validation = no errors.

In fact, the input even has the "valid" class at the time I validate the form (and still has it after)

However, neither of those things prevent the valid() method from returning that 0

Any ideas how to get the form to pass validation?


回答1:


Turns out the correct syntax to add conditional rules are:

TimeFrameAmount: { 
    required: { 
        depends : function () { 
            //check conditionality 
        } 
    } 
} 


来源:https://stackoverflow.com/questions/14953078/jquery-validation-conditional-rule-makes-input-never-valid-valid-always-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!