None of the ASP.NET provided validators allow you to perform conditional validation based on another control. However, you can achieve this by using a CustomValidator that performs validation on the client-side, server-side, or both (at a minimum, server-side validation is recommended). The validators work well in conjunction with wizards.
ASP.NET markup example:
<asp:DropDownList ID="OptionsDropDownList" runat="server">
<asp:ListItem Text="Website" />
<asp:ListItem Text="Search Engine" />
<asp:ListItem Text="Other" />
</asp:DropDownList>
<asp:TextBox ID="OtherTextBox" runat="server" />
<asp:CustomValidator ID="custvOptionsDropDownList" runat="server" ControlToValidate="OptionsDropDownList"
ValidateEmptyText="true" Display="Dynamic" ClientValidationFunction="validateOtherTextBox"
ErrorMessage="This field is required!" OnServerValidate="ValidateOtherTextBox" />
Javascript for ClientValidationFunction:
<script type="text/javascript" language="javascript">
function validateOtherTextBox(event, args) {
var textbox = document.getElementById('<%= OtherTextBox.ClientID %>').value;
if (args.Value == 'Other')
args.IsValid = (textbox != '');
else
args.IsValid = true;
}
</script>
Code-Behind for OnServerValidate:
protected void ValidateOtherTextBox(object source, ServerValidateEventArgs args)
{
if (OptionsDropDownList.SelectedValue == "Other")
{
args.IsValid = (OtherTextBox.Text.Trim() != "");
}
}
Note that it's your choice to implement whatever you need. You could completely skip Javascript validation and remove that code and the ClientValidationFunction
attribute. Also, notice that the Javascript refers to the target control by using the ClientID property. This is needed since ASP.NET assigns a different ID when the page is output and you'll want it to be provided to the Javascript method in this manner (view source on the page and you'll see that the control name has an extra prefix etc.).