Control referenced by the ControlToValidate property cannot be validated

February 3rd, 2011

Form validation is common, but surprisingly, the ASP.NET built in validation controls don’t work with the CheckBox (or CheckBoxList) web controls!
If you specify the ControlToValidate attribute in a validator to the ID of a CheckBox (and ValidationGroup too) then you will receive the following exception:
Control [ID] referenced by the ControlToValidate property of [ID] cannot be validated.

Although it could be perceived as a bug, it’s actually not because according to Microsoft a checkbox can only have valid values; checked or not… Which is true in theory but doesn’t really apply to reality when it comes to form validation, for instance when terms and conditions need to be accepted in a registration form.

Now, there are various solutions/workarounds for this problem, but even if you only need server validation most of the suggested solutions are quite time consuming.
An easy and pretty fast (and somewhat dirty but hey, that’s the way we like it) workaround is to trick ASP.NET into believeing we are validating a textbox instead of a checkbox. We keep the validators happy believing it’s validating a standard TextBox control while we hide it using CSS and use the validator to run our errands.

First, the code-in-front. Note the text value “dontremove” for the TextBox control, which is specified to make sure the validator will trigger. Without any text the validation will not occur.

?View Code ASPNET
1
2
3
<asp:CustomValidator ID="MyValidator" runat="server" ErrorMessage="Your error message here" ControlToValidate="TextBoxValidationFix" ValidationGroup="mygroup" Display="None" OnServerValidate="MyValidator_ServerValidate" />
<asp:TextBox ID="TextBoxValidationFix" runat="server" Text="dontremove" CssClass="invisible" Visible="false" />
<asp:CheckBox runat="server" id="MyCheckbox" />

Then we create the method for the validation…

?View Code CSHARP
1
2
3
4
protected void CustomValidatorTerms_ServerValidate(object source, ServerValidateEventArgs args)
{
	args.IsValid = MyCheckbox.Checked;
}

* UPDATE *
There is no need to hide the textbox control with CSS, since it works just as fine by just hiding it with a standard asp.net attribute: Visible=”false”

…and finally the CSS class to hide our partner in crime, the TextBox control.
input.invisible { visibility:hidden; }

Leave a Reply