How to incorporate Bootstrap has-error class on error while using data annotations

12,157

To solve this issue for myself, I created a CSS class as follows:

.has-error .form-control,
.input-validation-error {
   border: 1px solid #f44336 !important;
   -webkit-box-shadow: none !important;
   -ms-box-shadow: none !important;
   box-shadow: none !important;
}

It overrides the .input-validation-error class that ASP.NET puts on the form control that has an issue. No Javascript needed. It worked for me. I hope it helps you out.

Share:
12,157
Brendan Vogt
Author by

Brendan Vogt

Wedding photographer and videographer from Paarl, South Africa. Join me on my new adventure in wedding photography and videography at Brendan Vogt Photo & Video.

Updated on June 04, 2022

Comments

  • Brendan Vogt
    Brendan Vogt almost 2 years

    How do I add Bootstrap's has-error css class to a container div on a form error while using data annotations?

    I have the following property in my viewmodel class:

    [Display(Name = "First Name")]
    [Required(ErrorMessage = "Required")]
    public string FirstName { get; set; }
    

    First name is a required field. When the user clicks the submit button and nothing has been filled in then the Required error message is displayed beneath the textbox. The textbox's border is displayed in a reddish colour. Here is my css:

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

    Here is my Razor and HTML markup:

    <div class="form-group">
         @Html.LabelFor(m => m.FirstName, new { @class = "col-lg-2 control-label" })
         <div class="col-lg-4">
              @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control", placeholder = "Enter first name" })
              @Html.ValidationMessageFor(m => m.FirstName)
         </div>
    </div>
    

    What I am trying to achieve is that when there is an error, for example like what I explained above then I need the HTML markup to look something like this:

    <div class="form-group has-error">
    </div>
    

    How would I achieve something like this?

    I am using ASP.NET MVC 5 and the latest version of Bootstrap.