I want to show a ValidationSummary mcv3 with \"alert-error\" Bootstrap styling.
I\'m using a Razor view, and I show model errors with this code:
@Html.V
Expanding upon Daniel Björk's solution you can include a little script to adjust the CSS included with ValidationSummary()
output. The resulting bootstrap alert was showing a rendering issue until I removed the validation-summary-errors
class.
@if (ViewData.ModelState.Any(x => x.Value.Errors.Any())) {
<div class="alert alert-danger">
<a href="#" class="close" data-dismiss="alert">×</a>
<h4>Validation Errors</h4>
@Html.ValidationSummary()
</div>
}
<script>
$(".validation-summary-errors").removeClass("validation-summary-errors");
</script>
You can also easily give a bootstrap highlight to fields with errors. See http://chadkuehn.com/convert-razor-validation-summary-into-bootstrap-alert/
If it needs to work with clientside javascript I suggests doing this:
.validation-summary-valid {
display: none;
}
You still can assign the bootstrap class
@Html.ValidationSummary(null, new {@class= "alert alert-danger" })
but it will only show when you have actual errors.
To achieve the same in bootstrap 4, use the following:
@if (ViewData.ModelState[""] != null && ViewData.ModelState[""].Errors.Count() > 0)
{
<div class="col-auto alert alert-danger" role="alert">
@Html.ValidationSummary(true)
</div>
}
Based on the answers here:
@if (!ViewData.ModelState.IsValid)
{
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
@Html.ValidationSummary(false, "Errors: ")
</div>
}
(I'm using Bootstrap 4)
I took a slightly different route: using JQuery to hook into the form submit:
$('form').each(function() {
var theForm = $(this);
theForm.submit(function() {
if ($(this).valid()) {
if ($(this).find('.validation-summary-valid').length) {
$('.validation-summary-errors').hide();
}
} else {
if ($(this).find('.validation-summary-errors').length) {
$('.validation-summary-errors')
.addClass('alert alert-error')
.prepend('<p><strong>Validation Exceptions:</strong></p>');
}
}
});
});
I have this set inside a self-executing javascript module so that it hooks onto any validation summaries that I create.
HTH
Chuck
You can use jquery:
$(function(){
$('.validation-summary-errors.alert.alert-error.alert-block').each(function () {
$(this).prepend('<button type="button" class="close" data-dismiss="alert">×</button>');
});
});
It is looking for every div containing given error classes from bootstrap and writing html at beginning of the div. I am adding .alert-block
class as the bootstrap page says:
For longer messages, increase the padding on the top and bottom of the alert wrapper by adding .alert-block.