Change textbox's css class when ASP.NET Validation fails

前端 未结 6 2107
遥遥无期
遥遥无期 2020-12-01 09:27

How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the

6条回答
  •  鱼传尺愫
    2020-12-01 10:11

    Alternatively, just iterate through the page controls as follows: (needs a using System.Collections.Generic reference)

    const string CSSCLASS = " error";    
    
    protected static Control FindControlIterative(Control root, string id)
    {
       Control ctl = root;
       LinkedList ctls = new LinkedList();
       while ( ctl != null )
       {
         if ( ctl.ID == id ) return ctl;
         foreach ( Control child in ctl.Controls )
         {
           if ( child.ID == id ) return child;
           if ( child.HasControls() ) ctls.AddLast(child);
         }
         ctl = ctls.First.Value;
         ctls.Remove(ctl);
       }
       return null;
    }
    
    
    
    protected void Page_PreRender(object sender, EventArgs e)
    {
      //Add css classes to invalid items
      if ( Page.IsPostBack && !Page.IsValid )
      {
        foreach ( BaseValidator item in Page.Validators )
        {
           var ctrltoVal = (WebControl)FindControlIterative(Page.Form, item.ControlToValidate);
           if ( !item.IsValid ) ctrltoVal.CssClass += " N";
           else ctrltoVal.CssClass.Replace(" N", "");
        }
      }
    }
    

    Should work for most cases, and means you dont have to update it when you add validators. Ive added this code into a cstom Pageclass so it runs site wide on any page I have added validators to.

提交回复
热议问题