I am having an issue with the jquery validation plugin not removing the error class on blank entry (which is allowed) in this case. I am only applying one custom rule to the input which allows for empty input.
As an example...
- I input something invalid for the input like #### and the move to the next input.
- the input turns red and the error message shows below my fname field.
- I return to it and delete the '####'. Upon doing so the error message disappears, BUT the input still stays red. I can move in and out of the field and it still stays red.
- While just the input is red if I enter any single valid character in the now empty field the red disappears.
So, I guess my question is why the error message is removed correctly yet the class for the input is not being removed (highlighting in red)?
I have verified this in firebug... the has-error class is not being removed from <div class="col-md-6 form-group"> when I delete ####, but it is if I delete and enter a single valid character.
html:
<div class="col-md-6 form-group">
<label><b>First Name</b></label>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-user fa-fw"></i>
</span>
<input class="form-control" type="text" name="fname" <?php echo ($_SESSION['account']['fname'] ? 'data-default="true" value="'.$_SESSION['account']['fname'].'"' : 'placeholder="first name"'); ?>/>
</div>
<span class="help-block"></span>
</div>
js:
$('#account-info-form').validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block', // default input error message class
focusInvalid: false, // do not focus the last invalid input
rules: {
fname: {
cname: true
}
},
messages: {
fname: {
cname: "Enter a valid first name."
}
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.form-group').addClass('has-error'); // set error class to the control group
},
success: function (label) {
label.closest('.form-group').removeClass('has-error');
label.remove();
},
errorPlacement: function (error, element) {
error.insertAfter(element.closest('.input-group'));
}
});
// custom name (first or last) validation
$.validator.addMethod("cname", function (value,element) {
return this.optional(element) || /^[a-z][a-z .,\-]{0,31}$|^$/i.test(value);
},"Please enter a valid name.");
// return default values on blank and do not cause error (if valid)
$('input[data-default="true"]').on('blur', function() {
if ( $(this).val() == '' ) {
$(this).val( this.defaultValue );
$(this).valid();
}
});