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