user1202420
user1202420

Reputation: 79

Validate TextBox based on DropDownList selection

I need to validate TextBox based on Value selected in DropDownList controls. I have asp:TextBox and asp:DropDownList controls.

If user selects Yes option from the first dropdown he must type value in text box. How can I validate second box? Thanks for help.

Upvotes: 4

Views: 7502

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460208

The simplest approach is to set the DropDownList's AutoPostBack property to true and handle it's SelectedIndexChanged event. Then you can Enable/Disable the validator there.

Another approach is to use a CustomValidator. This validator is not dependent on a single control. You must write the validation rules on your own. For example the ClientValidationFunction:

<script type="text/javascript" >
    function ClientValidate(source, arguments) {
        var txt = document.getElementById('TextBox1');
        var ddl = document.getElementById('DropDownList1');
        var decision = ddl.options[ddl.selectedIndex].text;
        if(decision=='Yes'){
            arguments.IsValid = txt.value.length > 0;
        }else{
            arguments.IsValid = true;
        }
    }
</script>

<asp:DropDownList id="DropDownList1" runat="server">
    <asp:ListItem Selected="True">Yes</asp:ListItem>
    <asp:ListItem Selected="False">No</asp:ListItem>
</asp:DropDownList>
<asp:TextBox id="TextBox1" runat="server" />
<asp:Button ID="BtnSubmit" runat="server" Text="Submit" />

<asp:CustomValidator id="CustomValidator1"
       ValidateEmptyText="true"
       ControlToValidate="TextBox1"
       ClientValidationFunction="ClientValidate"
       OnServerValidate="ServerValidation"
       Display="Static"
       ErrorMessage="Please enter text!"
       runat="server"/>

Remember to always implement a OnServerValidate because you should not rely on javascript only(can be disabled). This is easy:

void ServerValidation(object source, ServerValidateEventArgs args){
    args.IsValid = DropDownList1.SelectedIndex == 1 || TextBox1.Text.Length > 0;
}

VB.NET

Protected Sub ServerValidation(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs)
    args.IsValid = DropDownList1.SelectedIndex = 1 OrElse TextBox1.Text.Length > 0
End Sub

Upvotes: 4

twilson
twilson

Reputation: 2062

Add a CustomValidator control, that validates the TextBox, from there you'll have to do something like this (assuming C#) in the CustomValidator_ServerValidate event handler:

bool valid = false;

if (dropDownList.SelectedValue.Equals("yes")) {
   valid = !String.IsNullOrEmpty(textBox.Text);
}

return valid;

Upvotes: 0

Add this code to your submit button.

if(DropDownList1.SelectedItem.Text.Equals("Yes") && TextBox1.Text.Length==0)
{
        Page.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Enter data in the textbox !');", true);
}

Upvotes: 0

Related Questions