如果需要字段验证的条件
If condition for required field validation
我在 c#.net 中有一个 DropDownList 和一个 TextBox。如果 DropDownList 值为 "No",则必须在 TextBox 中输入一些值。如果下拉列表值为是,则该文本框不需要必填字段验证器。如何让它成为可能?
<asp:DropDownList ID="dropdownlist1" runat="server"
CssClass="NormalText" Width="155px" AutoPostBack="true"
onselectedindexchanged="ddls_SelectedIndexChanged">
<asp:ListItem Selected="True" Value=""></asp:ListItem>
<asp:ListItem Value="Yes">Yes</asp:ListItem>
<asp:ListItem Value="No">No</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:TextBox ID="Textbox1" runat="server" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="Textbox1" ErrorMessage="Explanation needed If you select NO">
</asp:RequiredFieldValidator>
</td>
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
}
使用此代码进行条件验证:
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
if(dropdownlist1.SelectedValue == "No")
{
RequiredFieldValidator1.Enabled = true;
}
else if(dropdownlist1.SelectedValue == "Yes")
{
RequiredFieldValidator1.Enabled = false;
}
}
可选,您可能还必须设置提交按钮验证组:
ButtonSubmit.ValidationGroup = string.Empty;
未启用字段验证器时。
我在 c#.net 中有一个 DropDownList 和一个 TextBox。如果 DropDownList 值为 "No",则必须在 TextBox 中输入一些值。如果下拉列表值为是,则该文本框不需要必填字段验证器。如何让它成为可能?
<asp:DropDownList ID="dropdownlist1" runat="server"
CssClass="NormalText" Width="155px" AutoPostBack="true"
onselectedindexchanged="ddls_SelectedIndexChanged">
<asp:ListItem Selected="True" Value=""></asp:ListItem>
<asp:ListItem Value="Yes">Yes</asp:ListItem>
<asp:ListItem Value="No">No</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:TextBox ID="Textbox1" runat="server" CausesValidation="True"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="Textbox1" ErrorMessage="Explanation needed If you select NO">
</asp:RequiredFieldValidator>
</td>
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
}
使用此代码进行条件验证:
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
if(dropdownlist1.SelectedValue == "No")
{
RequiredFieldValidator1.Enabled = true;
}
else if(dropdownlist1.SelectedValue == "Yes")
{
RequiredFieldValidator1.Enabled = false;
}
}
可选,您可能还必须设置提交按钮验证组:
ButtonSubmit.ValidationGroup = string.Empty;
未启用字段验证器时。