title: Custom TextBox with built-in Validator: server side validation not firing
body: <p>I have a class that looks like this:</p>
  
  <pre><code>public class TextField : TextBox
  {
     public bool Required { get; set; }
     RequiredFieldValidator _validator;
  
     protected override void CreateChildControls()
     {
        base.CreateChildControls();
  
  
        _validator = new RequiredFieldValidator();
        _validator.ControlToValidate = this.ID;
        if(Required)
            Controls.Add(_validator);
     }
  
     public override void Render(HtmlTextWriter tw)
     {
        base.Render(tw);
  
        if(Required)
           _validator.RenderControl(tw);
     }
  }
  </code></pre>
  
  <p>This has been working for a while in a internal application where javascript is always enabled.  I recently noticed that an upstream javascript error can prevent the validators from firing, so the server side validation should kick in... right? right?</p>
  
  <p>So the Page.IsValid property always returns true (I even tried explicitly calling Page.Validate() before-hand).  </p>
  
  <p>After some digging, I found that the validator init method should add the validator to the page, but due to the way I'm building it up, I don't think this ever happens.  Thus, client side validation works, but server side validation does not.</p>
  
  <p>I've tried this:</p>
  
  <pre><code>protected override OnInit()
  {
     base.OnInit();
  
     Page.Validators.Add(_validator); // &lt;-- validator is null here
  }
  </code></pre>
  
  <p>But of course the validator is null here (and sometimes it's not required so it shouldn't be added)... but OnInit() is really early for me to make those decisions (the Required property won't have been loaded from ViewState for example).</p>
  
  <p>Ideas?</p>