Jaylen Jaylen - 2 months ago 20
jQuery Question

How can I override the jquery.unobtrusive settings work for css bootstrap styling?

This is my first time trying to use jQuery.Validation with jquery.unobtrusive that is shipped with ASP.NET MVC fresh project.

Before I used jquery.unobtrusive I use to override the defaults for the jQuery.Validator and everything worked perfectly like this

$.validator.setDefaults({
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});


Now, that I am using jquery.unobtrusive the spans don't get styles correctly when an error happens.

I tried to set the settings for jquery.unobtrusive which is not working. But this is what I did in attempt to set the settings for it

$(function(){
$.validator.unobtrusive.settings({
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
});


but that is giving me an error in the console

TypeError: $.validator.unobtrusive.settings is not a function


How can I correctly add css bootstrap for jquery.unobtrusive without having to add code for every form separately.

Answer

Make sure you load your scripts in the following order

  1. jQuery
  2. jQuery Validator
  3. Your defaults as you used in you question (This must be loaded before unobtrusive otherwise unobtrusive will override it
  4. jquery.Validator.unobtrusive

This is the code to use in step 3

$.validator.setDefaults({
    highlight: function (element) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function (element) {
        $(element).closest('.form-group').removeClass('has-error');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }
});

finally, you can add this to your css style to give the span the red color used in css bootstrap

.field-validation-error 
{
    color: #A94442;
}
Comments