Cascade trigger field validation in jquery

坚强是说给别人听的谎言 提交于 2020-08-26 10:14:51

问题


I have a form with two numeric input, let say input1 and input2.

I would like to have the following validation rules:

  • R1: input2 <= input1 * 0.2 (triggered when input1 or input2 values change)
  • R2: input1 <10

Forget for a moment R2 and look at this code:

<input id="input1" class="validation1"/>
<input id="input2" class="validation2"/>

$.validator.addMethod("validation2", function (value, element) {
  var v = Globalize.parseFloat(value);
  var l = Globalize.parseFloat($('#input1').val());
  return !l || !v || v <= l*0.2;
}, "Error");
$.validator.classRuleSettings.validation2= { validation2: true };

$.validator.addMethod("validation1", function (value, element) {
  var validator = $("form").validate();
  validator.element($('#input2'));
  return true;
}, "should never be shown");
$.validator.classRuleSettings.validation1= { validation1: true };

This code works pretty well. Validation of input2 is called when input1 or input2 change.

So let's add R2 by editing validation1 in this way:

$.validator.addMethod("validation1", function (value, element) {
  var validator = $("form").validate();
  validator.element($('#input2'));

  var v = Globalize.parseFloat(value);
  return v && v<10;
}, "Input1 must be less than 10");

This code works as expected but once that input1 is set greater than 10 it became red and it remains red also when value is changed to be <10.

Any idea?


回答1:


I can't get your code to function in a jsFiddle: http://jsfiddle.net/TcpnH/

Perhaps you can construct a jsFiddle.

Some notes:


1) IMPORTANT: All inputs must contain a name attribute or this plugin will not operate as intended. Even if you don't use that name for anything else in your jQuery, it's still required.

<input id="input1" name="input1" class="validation1" />

2) If input1 must simply be less than 10, why are you creating a whole new method for that? Simply use the built-in max method/rule. max: 10


3) $.validator.classRuleSettings.validation1= { validation1: true }; I don't see classRuleSettings anyplace in the documentation, nor do I see the purpose.

Typically a custom method/rule would be added as a class on the element, which you've already done:

<input id="input1" class="validation1" />

Otherwise, declared as a rule:

$('form').validate({
    rules: {
        myfieldname: {
            validation1: true
        }
    }
});


来源:https://stackoverflow.com/questions/15131445/cascade-trigger-field-validation-in-jquery

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