Using jQuery Validation plugin, I defined the following for my Bootstrap form:
$(".form-with-validation").validate({
errorClass: "help-block",
errorElement: "span",
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
}
});
It works well for a simple form. However, the part with highlight and unhighlight doesn't work when a .form-group contains multiple inputs (inline) that need to be validated:
<div class="form-group">
<label class="col-md-4 control-label">State & Zip</label>
<div class="col-md-3">
<select class="form-control required" name="state">
...
</select>
</div>
<div class="col-md-3">
<input type="text" class="form-control required" name="zip">
</div>
</div>
The problem is that once you select a state for example, the input becomes valid, and its .form-group parent loses .has-error class, even though the sibling input (i.e. zip) is still invalid (i.e. has a .help-block span below it):
So, I changed the unhighlight part to the following:
unhighlight: function(element) {
var formGroup = $(element).closest('.form-group');
var formGroupIsValid = true;
formGroup.find('input').each(function(){
if (! $(this).valid())
formGroupIsValid = false;
});
if (formGroupIsValid)
formGroup.removeClass('has-error');
}
Yet I get the following error:
Uncaught RangeError: Maximum call stack size exceeded
Any ideas why? I tried many approaches, but each time I get the same error.
EDIT
I'd prefer to stick with div.form-group having .has-error class if possible (because of styling).
EDIT 2
Jsfiddle to demonstrate the issue.
