Press enter to see results or esc to cancel.

How To Add Error Css Class To TextBox Using ASP.NET Validator Controls

The inbuilt Validator controls in ASP.NET do not let you specify an error css class for the control that’s being validated (ControlToValidate). Instead, the only thing you can set is the ValidationMessage that’s displayed in a span element next to the control.

Below is a simple solution that lets you set an error class on a TextBox control used together with any Validator control (e.g. RequiredFieldValidator) when that TextBox control is deemed invalid by said Validator control on a form button submit click. The solution requires the jQuery library in order to work.

The solution assumes the submit LinkButton has class FormsCommandSubmit (default class set by ASP.NET).

$(document).ready(function () {

  $('form a.FormsCommandSubmit').on('click',
    function (e) {
      if (Page_ClientValidate()) {
        return true;
      } else {
        $('form input:text').removeClass('error'); // remove any previously set class
        $.each(Page_Validators, function () {
          var validator = $(this)[0];
          if (validator != null) {
            var controltovalidate = validator.controltovalidate;
            if ( controltovalidate != null) { 
              ValidatorValidate(validator);
              if (!validator.isvalid) {
                $('#' + controltovalidate).addClass('error'); // re-set the class since the control is not valid.
              }
            }
          }
        });
        return false;
      }
    }
  );
});
Comments

Leave a Comment