Thursday, July 13, 2006

A validated check box in ASP.Net

As you probably know, there is no validator for a check box in ASP.Net. People go through hoops to make this work.

We just want to force the user to check the box before submitting. This is for scenarios like "click to accept agreement etc..."

The solutions I have found were not to my complete liking. So here is my solution to this annoying problem. It is very compact and involves very little javascript. It is a cool little trick. Have fun.


<%@ Control Language="C#" %>
<script runat="server">
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        _BoxMirror.Style.Add("display", "none"); // Hide the box. It is just there for the
        // validation logic to work.
        // Now hook up the check box to the text box. The text value mirrors the
        // value of the check box in sync.
        _Box.Attributes["onclick"] = "getElementById('" + _BoxMirror.ClientID + "').value=this.checked";
        _BoxMirror.Text = _Box.Checked.ToString().ToLower(); // Sync text box and check box
        // The validator Initial value is set to "false" so the Text Box will validate when
        // its value is different from "false".
    }
   
</script>

<div runat="server" id="_Wrapper" style="background-color:Yellow">
    <asp:TextBox runat="server" ID="_BoxMirror" />
    <asp:CheckBox runat="server" ID="_Box" />
    <asp:RequiredFieldValidator InitialValue="false"
    runat="server" Text="*" ID="_NeedToBeChecked" ControlToValidate="_BoxMirror" />
</div>


Sneak preview the all-new Yahoo.com. It's not radically different. Just radically better.

1 comment:

Anonymous said...

MONEY BAGS! you are the man, I can't believe ms would screw this up so bad. I am using your skills.