I have a code that I created in JS that you use along with jQuery Validator, where it validates all form fields that have the required attribute, so you do not have to validate one by one .
The only disadvantage is that it does not have a specific error message for each field and only validates whether the field was filled in or not, but I think it can help.
As @PapaCharlie said, it is a more aesthetic validation.
$('form').not('.no-validate').each(function(key, form) {
$(form).data('validator', $(form).validate({
ignore : "",
errorElement : false,
highlight : function(field) {
$(field).closest('.form-group, .input-group').addClass('has-error').removeClass('has-success');
},
unhighlight : function(field) {
$(field).closest('.form-group, .input-group').removeClass("has-error").addClass('has-success');
},
errorPlacement : function() {
}
}));
});
In order for this code to work you only have input
within div
with class form-group
or input-group
, and have in your CSS class has-error
and has-success
created, see below how I created the classes.
.has-error .form-control, .has-error input[type="email"]{
border-color: #A94442;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-success .form-control {
border-color: #3c763d;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
These two classes are present in Bootstrap if you use them.
In this code you can improve by adding a div
with the error message you want, or hide div
if the field is filled, etc.
It's just an idea and a quick and simple way to validate whether the required fields have been filled in.