CODEDIGEST InstallShield
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » CodeDigest » Conditionally validating a textbox when a checkbox is checked in ASP.Net   You are not logged in.
Search
 

Sponsors
InstallShield
 

Sponsored Links
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Conditionally validating a textbox when a checkbox is checked in ASP.Net
Conditionally validating a textbox when a checkbox is checked in ASP.Net
Submitted By Satheesh Babu
On 12/11/2008 8:01:55 AM
Tags: asp.net,CodeDigest,javascript  

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;

                }

            }

            return;       

        }

    </script> 

<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"

        ClientValidationFunction="RequirePersonalDetails"

        ValidateEmptyText="true">

    </asp:CustomValidator>

 

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!!