【问题标题】:How to validate required text when "Other" option is selected from a dropdownlist?从下拉列表中选择“其他”选项时如何验证所需的文本?
【发布时间】:2009-09-11 09:53:24
【问题描述】:
我的网站上有以下内容。
来源 [DropDownList]
网站
搜索引擎
其他
其他来源 [文本框]
我想使用 ASP.Net 验证器(我认为是比较验证器),以便在下拉列表中选择“其他”且未输入任何文本时触发验证并且无法提交页面。
这可能吗?
我尝试将下拉菜单中“其他”选项的值设置为 string.empty 并将其与空文本框进行比较,但这不起作用。
我继承的整个东西都在一个向导控件中,否则我会连接一些客户端脚本来自己触发验证。我不认为我可以使用向导控件来做到这一点?
提前致谢。
【问题讨论】:
标签:
asp.net
validation
drop-down-menu
【解决方案1】:
ASP.NET 提供的验证器都不允许您基于另一个控件执行条件验证。但是,您可以通过使用在客户端、服务器端或两者上执行验证的 CustomValidator 来实现这一点(至少,建议使用服务器端验证)。验证器与向导一起工作得很好。
ASP.NET 标记示例:
<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" />
用于 ClientValidationFunction 的 JavaScript:
<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>
OnServerValidate 的代码隐藏:
protected void ValidateOtherTextBox(object source, ServerValidateEventArgs args)
{
if (OptionsDropDownList.SelectedValue == "Other")
{
args.IsValid = (OtherTextBox.Text.Trim() != "");
}
}
请注意,您可以选择实现所需的任何内容。您可以完全跳过 Javascript 验证并删除该代码和 ClientValidationFunction 属性。另外,请注意 Javascript 通过使用 ClientID 属性来引用目标控件。这是必需的,因为 ASP.NET 在输出页面时分配了不同的 ID,并且您希望以这种方式将其提供给 Javascript 方法(查看页面上的源代码,您会看到控件名称有一个额外的前缀等)。
【解决方案2】:
然后像这样在下拉列表中的选择中检查 who 选项
if (ddl.selecteditemindex == 1){
if (txtvalue.text == "")
{
alert('you write something if selected other otherwise choose from a list');
}
}