1

I want to change the CssClass to txtbox300CommentRED if validation in asp.net fails.

I cant find a way to do is this. Is it possible that we can tell RequiredFieldValidator or other Validators to change the CssClass class of txtFullName if validation fails?

<asp:TextBox ID="txtFullName" runat="server" CssClass="txtbox300Comment"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>

How can I achieve this and what is hassle free or professional way to do it.

Help is appreciated.

Rich
  • 1,895
  • 3
  • 26
  • 35
Learning
  • 19,469
  • 39
  • 180
  • 373
  • I cant use MVC it is purely a web form project – Learning Jan 26 '12 at 13:30
  • Look at this: [http://stackoverflow.com/questions/1301508/change-textboxs-css-class-when-asp-net-validation-fails][1] [1]: http://stackoverflow.com/questions/1301508/change-textboxs-css-class-when-asp-net-validation-fails – Meh Man Sep 27 '13 at 18:51

3 Answers3

3

The ErrorMessage attribute of the RequiredFieldValidator can contain all kinds of HTML tags, so you can put Javascript in it.

ErrorMessage="Bad! <script type='text/javascript'>changeclass();</script>"
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
2

You can access the validator spans from javascript, and change the css class of the control they are validating. You can run this script on submit. However, I'm not sure how to determine whether a specific control is valid or not.

E.g. if you have a css class "error", you can do the following:

if (Page_ClientValidate() == false)
{
    if (Page_Validators != null)
    {
        for (i = 0; i < Page_Validators.length; i++)
        {
            var validatedControl = 
                document.getElementById(Page_Validators[i].controltovalidate);
            validatedControl.className = "error";
        }
    }
}

See How to skin all ASP.Net validators? for more information.

Unfortunately, WebForms is not suited well for this. I would recommend going with MVC if possible, or trying out xVal for WebForms, an open source validation library built on DataAnnotations and jQuery Validate.

Community
  • 1
  • 1
jrummell
  • 42,637
  • 17
  • 112
  • 171
1

ControlToValidate="txtFullName" is set on the RequiredFieldValidator

if(!RequiredFieldValidator1.IsValid){
    //You might have to adjust where its looking for the control
    TextBox txt = form1.FindControl(RequiredFieldValidator1.ControlToValidate) as TextBox;
    if (txt != null)
    {
        txt.CssClass = "txtbox300Comment";
    }

}
zeal
  • 740
  • 1
  • 4
  • 31