Chung Lun Yuen Chung Lun Yuen - 1 year ago 106
Javascript Question

jQuery .validate throws exception when focus out. Says "check 'depend' method"

I am working on jquery form validation, using the jQuery .validate plugin. There is a text field (name: "yo_text") that is required only when a radio button (in this case, "Hey Yo") is checked.

Now jQuery can tell yo_text depends on "Hey Yo" being selected, but an error crops up every time when yo_text blurs and is not empty. The error message at the text field does not go away too, if previous check said it was invalid (that is, yo_text being empty)

The error:

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


I had simply modified the code form .validate's example (see below), but now the mysterious error appears. I can't figure out where the problem comes from.

So the markup:

<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>


And the script:

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
}
}
});


And the example I modified from in .validate's documentation:

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


And a JSFiddle for reference:

https://jsfiddle.net/vzj1ckbx/

Thanks for any help in advance!

Answer Source

There is an issue in your function isYo, I think it should return a Boolean value which was not. In your case it will return the element. Also some modifications in the validate also.

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;
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download