Form Validation Formatting in ASP.NET MVC 5 and Bootstrap 3

When creating a new MVC project in ASP.NET MVC 5, Bootstrap is already included. For some reason proper formatting for form errors (the red colored error message and the red border around the controls) are not working. There are loads of articles and blog posts how to change this and that to enable this, but in ASP.NET MVC 5, the only thing you actually have to do is add a few classes to your Site.css file. Why they aren’t in there from the outset I don’t know.

Site.css

/* styles for validation helpers */
.field-validation-error {
color: #b94a48;
}

.field-validation-valid {
display: none;
}

input.input-validation-error {
border: 1px solid #b94a48;
}


select.input-validation-error {
border: 1px solid #b94a48;
}

input
[type="checkbox"].input-validation-error {
border: 0 none;
}

.validation-summary-errors {
color: #b94a48;
}

.validation-summary-valid {
display: none;
}

Sample form.cshtml

@model WebApplication6.Models.TestModel

@{
ViewBag.Title = "Home Page";
}
<br /><br />

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
<br />
@Html.ValidationMessageFor(m => m.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.GenderId, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.GenderId, new SelectList(Model.Genders, Model.GenderId), "", new { @class = "form-control" })
<br />
@Html.ValidationMessageFor(m => m.GenderId)
</div>
</div>


<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="OK" />
</div>
</div>
}


Sample TestModel.cs

public class TestModel
{
[Required(ErrorMessage = "Name is required")]
[MinLength(3, ErrorMessage = "Name must be at least 3 letter")]
public string Name { get; set; }
[Display(Name= "Gender")]
[Required(ErrorMessage = "Gender is required")]
public string GenderId { get; set; }

public string[] Genders = new[] {"Male", "Female"};
}


No Comments