Reputation: 717
Im trying to make sure that all fields are validated before submitting a form. I don't even know really where to start. I would like to have the submit button greyed out or just disabled until all the fields are successfully validated.
Here is the script:
$('document').ready(function(){
$('form').validate({
rules: {
a: {required:true, minlength:2},
b: {required:true}
},
messages: {
a: {required: "enter your name!"},
b: {required: "enter the date!"}
},
errorPlacement: function(error, element) {
if(element.attr('name') == 'a'){
$('#name').html(error);
}
if(element.attr('name') == 'b'){
$('#date').html(error);
}
},
success: function(label){
label.addClass("valid").text("Ok!");
},
debug:true
});
$('#a').blur(function(){
$("form").validate().element("#a");
});
});
Here is the html:
<form action="#" id='commentForm'>
<input type="text" name="a" id="a">
<input type="text" name="b" id="b">
<button type="submit">Validate!</button>
<div id="date" style="border:1px solid blue;"></div>
<div id="name" style="border:1px solid red;"></div>
</form>
And here is the jsfiddle:
Thanks a ton in advance!
Upvotes: 2
Views: 7616
Reputation: 3247
Without arguing if it's redundant or not (I personally like it since it's twice as clear this way)
If it is, enable the button.
$('input').blur(function(){
var thisform = $('form');
if (thisform.valid()) {
thisform.find("button").prop("disabled", false)
}
});
Fiddle: http://jsfiddle.net/wQxQ8/17/
You can also change blur to onkeyup, so it validates after each keystroke. It can have a performance hit though if you have a lot of inputs to validate.
Upvotes: 1