Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the CSS class of an input on validation error with razor

In my ASP MVC 3 application, I have this form

@using (Html.BeginForm())
  {
    <input id="Username" name="UserName" type="text" value="Username" class="form-text" />
    <input id="PasswordTxt" name="PasswordTxt" type="text" value="Password" class="form-text" />
    <input id="Password" name="Password" type="password" class="form-text" style="display: none"/>
    <input id="bt_login" type="submit" value="Log in" class="bt_login" />
    <div class="login_lbl_error">
      @Html.ValidationSummary()
    </div>
  }

I want to change the class of each wrong text field to "login_lbl_error".

Any ideas ?

Thanks.

like image 996
kbaccouche Avatar asked Mar 28 '12 08:03

kbaccouche


3 Answers

With MVC3, an input-validation-error CSS class will automatically be added to to the input elements which have validation errors.

Therefore in your CSS you can style this class:

.input-validation-error
{
   color:red;
}
like image 164
Curtis Avatar answered Sep 28 '22 17:09

Curtis


By default MVC adds input-validation-error and field-validation-error, you can use JQuery to override these classes:

<script type="text/javascript">
    $(document).ready(function(){
        $('.input-validation-error').addClass('CustomErrorClass').removeClass('input-validation-error');
        $('.field-validation-error').addClass('CustomErrorClass').removeClass('field-validation-error');
    });
</script>
like image 23
Muhammad Mobeen Qureshi Avatar answered Sep 28 '22 19:09

Muhammad Mobeen Qureshi


Since ASP.NET MVC adds the field-validation-error class to the error message element, and input-validation-error to form controls, I just changed the class name using jQuery:

$(".input-validation-error").toggleClass("input-validation-error newClassName");
like image 36
dekanidze Avatar answered Sep 28 '22 17:09

dekanidze