Skip to content

Instantly share code, notes, and snippets.

@carlin-q-scott
Last active May 31, 2024 14:07
Show Gist options
  • Save carlin-q-scott/467444ee864f83a34af3ddc87086b89d to your computer and use it in GitHub Desktop.
Save carlin-q-scott/467444ee864f83a34af3ddc87086b89d to your computer and use it in GitHub Desktop.
ASP.NET Unobtrusive Validation for Bootstrap 5
(function ($) {
// Make ASP's unobtrusive validation compatible with Bootstrap 5 styling. See this for more details: https://stackoverflow.com/a/19006517/576153
$.validator.setDefaults({
errorElement: "span",
errorClass: "invalid-feedback",
highlight: function (element, errorClass, validClass) {
// Only validation controls
if (!$(element).hasClass('novalidation')) {
$(element).closest('.form-control').removeClass('is-valid').addClass('is-invalid');
}
},
unhighlight: function (element, errorClass, validClass) {
// Only validation controls
if (!$(element).hasClass('novalidation')) {
$(element).closest('.form-control').removeClass('is-invalid').addClass('is-valid');
}
},
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
}
else if (element.prop('type') === 'radio' && element.parent('.radio-inline').length) {
error.insertAfter(element.parent().parent());
}
else if (element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
error.appendTo(element.parent().parent());
}
else {
error.insertAfter(element);
}
}
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment