How to validate required text when "Other" option is selected from a dropdownlist?



I have the following on my website.

Source [DropDownList]


Search Engine


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.

2 ответов


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: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 != '');
            args.IsValid = true;

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


you check then who option in select in dropdownlist like this

if (ddl.selecteditemindex == 1){
if (txtvalue.text == "")
alert('you write something if selected other otherwise choose from a list');