Check TextBox based on DropDownList selection

I need to check a TextBox based on the value selected in the DropDownList controls. I have asp:TextBox and asp:DropDownList controls.

If the user selects Yes from the first drop-down list, he must enter a value in the text box. How can I check the second box? Thanks for the help.

+4
source share
3 answers

The easiest way is to set the DropDownList AutoPostBack property to true and handle the SelectedIndexChanged event. Then you can enable / disable the validator there.

Another approach is to use CustomValidator . This validator is independent of one control. You must write the verification rules yourself. For example, 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 that always run OnServerValidate , because you should not rely only on javascript (you can disable it). 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 
+4
source

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); } 
0
source

Add a CustomValidator control that checks the TextBox , from there you should 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; 
0
source

Source: https://habr.com/ru/post/1395841/


All Articles