The RequiredField Validator for the TextBox can be enabled or disabled by checking or unchecking the CheckBox respectively.
You can specify that a user must provide information in a specific control on an ASP.NET Web page by adding a RequiredFieldValidator control to the page and linking it to the required control. For example, you can specify that users must fill in a Name text box before they can submit a registration form.
javascript function for client side validation (using jQuery)...
function CheckBoxRequired_ClientValidate(sender, e)
{
e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');
}
code-behind for server side validation...
protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = MyCheckBox.Checked;
}
ASP.Net code for the checkbox & validator...
<asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
OnServerValidate="CheckBoxRequired_ServerValidate"
ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>
and finally, in your postback - whether from a button or whatever...
if (Page.IsValid)
{
// your code here...
}
C# version of andrew's answer:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Please accept the terms..."
onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<asp:CheckBox ID="CheckBox1" runat="server" />
Code-behind:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = CheckBox1.Checked;
}
If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control
public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
{
get
{
if (_ctrlToValidate == null)
_ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;
return _ctrlToValidate;
}
}
protected override bool ControlPropertiesValid()
{
if (this.ControlToValidate.Length == 0)
throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));
if (this.CheckBoxToValidate == null)
throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));
return true;
}
protected override bool EvaluateIsValid()
{
return CheckBoxToValidate.Checked;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Visible && this.Enabled)
{
System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
}
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
{
cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
}
}
}
private string GetClientSideScript()
{
return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
}
}
Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.
The .ascx:
<script type="text/javascript">
function checkAgreement(source, args)
{
var elem = document.getElementById('<%= chkAgree.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
function checkAge(source, args)
{
var elem = document.getElementById('<%= chkAge.ClientID %>');
if (elem.checked)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
</script>
<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />
<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAgreement">
You must agree to the terms and conditions.
</asp:CustomValidator>
<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
ClientValidationFunction="checkAge">
You must be 18 years or older to continue.
</asp:CustomValidator>
And the codebehind:
Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
e.IsValid = chkAgree.Checked
End Sub
Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
e.IsValid = chkAge.Checked
End Sub
I typically perform the validation on the client side:
<asp:checkbox id="chkTerms" text=" I agree to the terms" ValidationGroup="vg" runat="Server" />
<asp:CustomValidator id="vTerms"
ClientValidationFunction="validateTerms"
ErrorMessage="<br/>Terms and Conditions are required."
ForeColor="Red"
Display="Static"
EnableClientScript="true"
ValidationGroup="vg"
runat="server"/>
<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" CausesValidation="true" Text="Submit" ValidationGroup="vg" runat="server" />
<script>
function validateTerms(source, arguments) {
var $c = $('#<%= chkTerms.ClientID %>');
if($c.prop("checked")){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With