Reputation: 283133
I've got a custom datepicker widget which I want to validate using jQuery.validate. When I modify my date it doesn't revalidate, presumably because the change event isn't firing on underlying hidden to which jQuery.validate is bound.
Through my research I've found that I can revalidate a single field by calling $('#mydatepicker').valid()
. I can put this in the on-change handler of my custom widget.
In theory, this should work, but my widget's on-change event fires once before jQuery.validation is initialized. This seems to break jQuery.validate completely.
So I'm looking for a way to determine if jQuery.validate has been initialized for this particular element. i.e., to determine if jQuery.validate is attempting to watch it.
I tried
if($input.valid) $input.valid();
But I think the method exists regardless if jQuery.validate has been initialized yet.
To be clear, the structure of my HTML looks like this:
<form id="myform">
<input id="mywidget" type="hidden">
<script>$('#mywidget').initializeMyCustomWidget();</script>
</form>
<script>
$('#myform').validate({ myOptions });
</script>
Upvotes: 1
Views: 1285
Reputation: 98738
But I think the method exists regardless if jQuery.validate has been initialized yet.
You cannot use .valid()
before .validate()
is initialized.
However, since one would typically initialize .validate()
on DOM ready, this should never be an issue.
.validate()
needs to be called on the form before checking it using this method.
So I'm looking for a way to determine if jQuery.validate has been initialized for this particular element. i.e., to determine if jQuery.validate is attempting to watch it.
Simply initialize the plugin on DOM ready so it can "watch" the form for triggering events.
$(document).ready(function() {
$('#myform').validate({
// rules, options, etc.
});
});
Upvotes: -1
Reputation: 283133
I took a peek at what the .valid
method actually does. It runs this:
$( this[ 0 ].form ).validate()
i.e. if you haven't called .validate()
yet then it's going to apply an empty validator to your form, with whatever default rules apply. This is why it was breaking my form.
The only way I could figure out how to check if my form already has a validator is by checking if the form has the data property validator
. I'm not sure how reliable this is.
I wrote this jQuery extension to "maybe" validate a specific field.
/**
* Validate inputs iff the form has a validator.
*/
$.fn.maybeValidate = function() {
var valid = true;
this.each(function() {
if(this.form && $(this.form).data('validator')) {
valid = $(this).valid() && valid;
}
});
return valid;
}
This works great for my use case because I can just call that method inside all my widget onchange callbacks. If a validator is bound, it'll revalidate the field. If not, no harm done.
Upvotes: 2