Home » CodeDigest


Conditionally validating a textbox when a checkbox is checked in ASP.Net
Submitted By Satheesh Babu B
On 12/11/2008 8:01:55 AM

Conditionally validating a textbox when a checkbox is checked in ASP.Net

Sometimes, when we build an input processing forms we might come across situations where we need to validate controls based on some conditions. For example, we can make a textbox to be required field only when a checkbox is checked or a dropdownlist value, etc.


This little article will provide you a code snippet that makes a textbox called txtName as required field when a checkbox with id chkRequired is checked. We make use of custom validator control to achieve this.


<script language="javascript">

        function RequirePersonalDetails(source, args) {           

            var chk = document.getElementById('chkRequired');

            var Name = document.getElementById('txtName');

            if (chk.checked) {

                if (Name.value.length <= 0) {

                    args.IsValid = false;


                else {

                    args.IsValid = true;






<asp:CheckBox ID="chkRequired" runat="server" Text="Required Personal Details" />

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

    <asp:CustomValidator ID="CustomValidator1" runat="server"

        ErrorMessage="Enter Your Name" ControlToValidate="txtName"





Remember to make the ValidateEmptyText preoperty of custom validator to true to check the validation for empty text else validation will be fired only when there is something entered on the control that is set in ControlToValidate property.

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..