I have the following on my website.
Source [DropDownList]
Website
Search Engine
Other
Other Source [TextBox]
I want to use the ASP.Net validators (I think the compare validator) so that when "Other" is selected in the dropdownlist and no text is entered the validation is triggered and the page cannot be submitted.
Is this possible?
Ive tried to set the value of the "Other" option in the drop down to string.empty and compare it to an empty text box but this didn't work.
The whole thing that I have inherited is inside a wizard control, otherwise I would hook up some client script to trigger the validation myself. I don't think I can do this with a wizard control?
Thanks in advance.
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.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With