Search code examples
javascriptasp.netcssrequiredfieldvalidator

required field validator asp.net change css of textbox


Instead of showing an error message 'Name is required' I would like to change (or also include) changing the background of the textbox to red (by the client side, the same way the error text is displayed). I imagine I have to use a javascript function.

Can anyone enligthen me please?

    <tr>
      <td>
         <asp:Label ID="lblName" runat="server" Text="Name" CssClass="bold" />
      </td>
      <td>
         <asp:TextBox ID="txtName" runat="server" TextMode="SingleLine" MaxLength="50" CssClass="textbox" />
      </td>
      <td>
         <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtName" Display="Static" Text="Name is required!" Enabled="true" CssClass="validator" />
      </td>
    </tr>

Solution

  • You can do it either by using jquery or by using a custom validator. Custom Validator might be a little easier and cleaner than jquery but both would accomplish the same thing.

    I found this blog post that might help you out: http://codinglifestyle.wordpress.com/2009/09/16/change-background-color-of-invalid-controls-asp-net-validator/