2012-02-10 40 views
4

我需要根据DropDownList控件中选择的值验证TextBox。我有asp:TextBoxasp:DropDownList控件。验证基于DropDownList选择的文本框

如果用户从第一个下拉列表中选择Yes选项,则必须在文本框中输入值。我如何验证第二个盒子?感谢帮助。

+0

你说的验证意思?验证什么?它不是空白的?它只包含数字?等等...... – Icarus 2012-02-10 21:16:14

回答

4

最简单的方法是将DropDownList的AutoPostBack属性设置为true并处理它的SelectedIndexChanged事件。然后你可以在那里启用/禁用验证器。另一种方法是使用CustomValidator。该验证器不依赖于单个控件。您必须自行编写验证规则。例如,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"/> 

记住要始终贯彻一个OnServerValidate,因为你不应该依赖于JavaScript只(可禁用)。这很容易:

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 
+0

谢谢蒂姆,你的回答是最好的! – user1202420 2012-02-10 21:34:47

+0

比你应该选择作为答案。 – AJP 2012-02-10 21:43:17

0

将此代码添加到您的提交按钮。

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

添加CustomValidator控制,即验证TextBox,从那里你必须在CustomValidator_ServerValidate事件处理程序做这样的事情(假设C#):

bool valid = false; 

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

return valid;