The Sample:
Lets say you have a checkbox and a DropDownList, and you want the DropDownList to have validation on it only when the checkbox is checked. When the checkbox is not checked you want the DropDownList disabled. Okay, sounds pretty simple, but can we do it without a postback.
Toggling the Disabled property
The JavaScript to toggle the DropDownList disabled property can be done like so:
<script type="text/JavaScript">
function Change(chkfield,field)
{
if (chkfield.checked == true)
{ document.getElementById(field).disabled = false; }
else
{ document.getElementById(field).disabled = true; }
}
</script>
Notice that I'm passing in the checkbox object and the field to be disabled. The DropDownList will be called "dd1."
In the checkbox you just plug in the function like so:
<input id="chk1" title="chk1" onclick="Change(this,'dd1')" type="checkbox" value="X" name="chk1">MyCheckBox
Adding the CustomValidator
Next we add the CustomValidator control after the checkbox. The code would like the following:
<asp:CustomValidator
ID="CustomValidator1" runat="server" ClientValidationFunction="Checkit" ControlToValidate="dd1"
ErrorMessage="Required Field" Font-Size="Large">*</asp:CustomValidator>
With the CustomValidator control you can supply a "ClientValidationFunction" that will be called. Remember to provide a server-side function as well because if you don't it can be a security risk according to Microsoft. For this example I left that out.
The Validation Function
The validation function, called "Checkit" in this example, will check the validation of the DropDownList "dd1."
This function would look like this:
function Checkit(sender, args)
{
if(!document.getElementById(sender.controltovalidate).disabled && args.Value=="bad")
{
args.IsValid=false;
}else{
args.IsValid=true;
}
}
Anyway, that's it for the Custom Validator control. Another cool control in the ASP.NET arsenal.
Happy Coding!
DX Jas