None of the ASP.NET validators provided allows for conditional validation based on another control. However, you can achieve this using CustomValidator, which performs client-side, server-side, or both (at least server-side verification is recommended). Validators work well with masters.
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 for OnServerValidate:
protected void ValidateOtherTextBox(object source, ServerValidateEventArgs args) { if (OptionsDropDownList.SelectedValue == "Other") { args.IsValid = (OtherTextBox.Text.Trim() != ""); } }
Please note that it is your choice to implement everything you need. You can completely skip Javascript validation and remove this code and the ClientValidationFunction attribute. Also note that Javascript references the target control using the ClientID property. This is necessary because ASP.NET assigns a different identifier when the page is displayed, and you want it to be provided to the Javascript method this way (look at the source code on the page and you will see that the control name has an additional prefix, etc. .).
Ahmad mageed
source share