Skip to content

Instantly share code, notes, and snippets.

@Danthar
Created November 21, 2013 12:43
Show Gist options
  • Save Danthar/7580931 to your computer and use it in GitHub Desktop.
Save Danthar/7580931 to your computer and use it in GitHub Desktop.
Javascript shim to properly add bootstrap 3 styling to validation helpers et al in asp.net MVC 4
$(function () {
$('span.field-validation-valid, span.field-validation-error').each(function () {
$(this).addClass('help-block col-xs-12 col-sm-reset inline');
});
$('.validation-summary-errors').each(function () {
$(this).addClass('alert');
$(this).addClass('alert-error');
$(this).addClass('alert-block');
});
$('form').submit(function () {
if ($(this).valid()) {
$(this).find('div.form-group').each(function () {
if ($(this).find('span.field-validation-error').length == 0) {
$(this).removeClass('has-error');
}
});
}
else {
$(this).find('div.form-group').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).addClass('has-error');
}
});
$('.validation-summary-errors').each(function () {
if ($(this).hasClass('alert-error') == false) {
$(this).addClass('alert');
$(this).addClass('alert-error');
$(this).addClass('alert-block');
}
});
}
});
$('form').each(function () {
$(this).find('div.form-group').each(function () {
if ($(this).find('span.field-validation-error').length > 0) {
$(this).addClass('has-error');
}
});
});
$("input[type='password'], input[type='text']").blur(function () {
if ($(this).hasClass('input-validation-error') == true || $(this).closest(".form-group").find('span.field-validation-error').length > 0) {
//$(this).addClass('error');
$(this).closest(".form-group").addClass("has-error");
} else {
//$(this).removeClass('error');
$(this).closest(".form-group").removeClass("has-error");
}
});
//Update the validator, you might want to check if the unobtrusive validation is loaded
$.validator.setDefaults({
highlight: function (element) {
$(element).closest(".form-group").addClass("error");
},
unhighlight: function (element) {
$(element).closest(".form-group").removeClass("error");
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment