I am using jQuery Validate to validate a form. Individual fields validate as desired, but my project demands the form's submit activate only after all validation checks successfully pass. (I'm aware of the UX problems with this, the decision is out of my hands.)
I am struggling to enable the submit button immediately even when I know validation is successful. My code doesn't return true until the user triggers another change
event:
$('#submit').attr('disabled', 'disabled');
$('form').validate({
onfocusout: function(element) { $(element).valid(); }, //I need each field to validate as it is typed into, per a client requirement
rules: {
name_required: "required",
name_number: "number",
name_required_select: "required"
}
});
//*THIS* is where I'm going wrong
$('input').on('blur keyup', function(){
if( $('form').validate().checkForm() ){
$('#submit').attr('disabled', '');
}
});
I know something's wrong because if I call $('form').validate().checkForm()
from the console I see the individual validation checks pass (without needing to click in/change any other field), and I get true
. For some reason I just can't get that when binding to keyup
and other events on my input
s.
Test case to demonstrate problem.
- Type anything in the first field, select something for the third field.
- The submit button should activate (the required validation rules are now met).
- Clicking inside any field, or entering a value in the optional fields, will activate my submit button.
Desired behaviour:
I need the submit button to activate immediately upon passing validation checks, without this extra step of going back and changing something.
What I've tried:
- Binding to
change
,keyup
, andblur
for allinput
s in every combination I can think of, doesn't help. - A nasty hack using
setInterval
and waiting untilvalid()
returns true, which works but I worry about constantly running that (this form is very long and the user will be on the page for a while). - I know the library has a
validate()
method but for some reason it triggers a validation check I don't want at that time (if( $('form').validate() ){ ...
). All I need is a boolean true/false, so that method wasn't suitable for my purposes. I feel I need to usecheckForm()
which doesn't trigger validation when invoked.