【问题标题】:Add/remove jQuery Validation rule based on Ajax request根据 Ajax 请求添加/删除 jQuery Validation 规则
【发布时间】:2019-03-16 16:22:16
【问题描述】:

我在根据 Ajax Get 请求从 jQuery Validation 更改特定规则时遇到问题。

我有一个由一个父表单和两个由 Jquery.post 请求更新的子表单组成的表单。这两个子表单在提交时会更新保存到各自隐藏输入中的计数器,并且在计数器需要至少为两者注册一个项目的条件下进行验证工作正常...... 直到规则变得更复杂。

现在,根据保存的第一个子表单的项的值,“min”规则是否必须激活。

示例:项目的代码值在 200 到 500 之间;如果至少有一项注册的代码大于或等于 300,则必须应用“最小”规则,否则不需要。问题是它必须动态解决,因为如果从第一个子表单列表中删除代码 >= 300 的项目,或者如果没有任何具有该代码值的项目然后保存其中一个,验证规则必须更新。

我已经尝试在 $.post 成功函数返回时更新规则,它只添加规则,从不删除它:

$.get('{url of the updating form}', function(data){
    if (data >=300) {
       $('#counter_form_child_2').rules('add', { min: 1 });
    } else {
       $('#counter_form_child_2').rules('remove'); //removes all rules for this input
    }
});

尝试进行返回 bool(true 或 false)的查询,搜索是否有任何代码 >=300 的项目并将其放入另一个隐藏字段:

//Code inside the js function that returns the boolean value
$.get('{url of the updating form}', function(data) {
     $('#item_above_300').val(data); //puts value into hidden field
});

//Code inside form validation rules
$("#parentForm").validate({
   ignore: ':hidden:not(#counter_form_child1, #counter_form_child1),
   rules : {
      (...)
      counter_child_form1: { min: 1 },
      counter_child_form2: { 
         min: { param: 1,
           depends: function(element) {
               return $('#item_above_300').val() === 1;
           }
         }
       }
     }
});

我需要一些帮助,因为我已经厌倦了尝试几种替代方法,但没有任何效果。非常感谢!

【问题讨论】:

    标签: javascript jquery validation dynamic rules


    【解决方案1】:

    最后,问题实际上不在规则上...
    使用 showErrors 测试有效字段,我可以调试并发现隐藏字段正在正确更新并且错误计数:

    showErrors: function(errorMap, errorList) {
       var submitted = true;
       if (submitted) {
          var summary = "Precisa corrigir os seguintes erros: <br/>";
          $.each(errorMap, function(name, value) { 
             summary += " * (" + name +  + value + "<br/>"; 
          });                   
          $("#msg_aviso").html(summary);
          submitted = false;
       }
       this.defaultShowErrors();
    }
    

    然后我发现问题出在errorMessage显示上。 并且仅在 counter_child_form2 消息中。 因此,在对 Stack Overflow 上的一些问题进行研究后,我发现解决方案是重置 DIV,该 DIV 会在每个提交表单事件时显示特定的错误消息。而且...瞧,它奏效了!

    $('#parentForm').click(function(){
        $("#counter_child_form2_error .error").html('');
        $("#parentForm").submit();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多