【问题标题】:jQuery .validate throws exception when focus out. Says "check 'depend' method" [duplicate]jQuery .validate 聚焦时抛出异常。说“检查'依赖'方法”[重复]
【发布时间】:2018-01-02 14:36:03
【问题描述】:

我正在使用 jQuery .validate 插件进行 jquery 表单验证。有一个文本字段(名称:yo_text“)只有在单选按钮(在这种情况下,嘿yo”)时才需要。

现在 jQuery 可以告诉 yo_text 依赖于被选中的“Hey Yo”,但是每次 yo_text 模糊并且不为空时都会出现错误。文本字段的错误消息也不会消失,如果之前的检查说它是无效的(即 yo_text 为空)

错误:

Uncaught TypeError: Cannot read property 'call' of undefined. Exception occurred when checking element , check the 'depends' method.

我只是简单地修改了 .validate 示例的代码形式(见下文),但现在出现了神秘的错误。我无法弄清楚问题出在哪里。

所以标记:

<form>
  <div class="radio">
    <label>
      <input type="radio" name="selection" value="yo"> Hey Yo
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" name="selection" value="ya"> Hey Ya
    </label>
  </div>
  <input class="form-control" type="text" name="yo_text" placeholder="Enter if yo">
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

还有脚本:

var form = $('form');

function isYo() {
  return form.find('input[type="radio"][name="selection"][value="yo"]')
}
form.validate({
  rules: {
    selection: 'required'
    , yo_text: {
      required: true,
      depends: isYo
    }
  }
});

还有我在.validate's documentation中修改的例子:

$("#myform").validate({
  rules: {
    contact: {
      required: true,
      email: {
        depends: function(element) {
          return $("#contactform_email").is(":checked");
        }
      }
    }
  }
});

还有一个 JSFiddle 供参考:

https://jsfiddle.net/vzj1ckbx/

提前感谢您的帮助!

【问题讨论】:

    标签: javascript jquery forms jquery-validate


    【解决方案1】:

    你的函数isYo 有问题,我认为它应该返回一个布尔值,但不是。在您的情况下,它将返回元素。验证中也有一些修改。

    https://jsfiddle.net/vzj1ckbx/4/

    var form = $('form');
    
    function isYo() {
     return $('input[type="radio"][name="selection"][value="yo"]').is(':checked');
    
    }
    form.validate({
        rules: {
            "yo_text": {            
                required: {
                    param:true,
                    depends: isYo
                }
            }
        },
        submitHandler: function () {
                alert('Ho hey')
            event.preventDefault();
            return false;
        }
    });
    

    【讨论】:

    • 谢谢!这行得通!也找到了解决方案的后半部分here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    相关资源
    最近更新 更多