我需要创建几个场景:
1) 如果下拉菜单有特定值,则将特定文本框设置为必填字段。
2) 如果特定的文本框有数据,则需要另一个文本框(如果填写了地址字段,则需要城市、州和邮政编码)
我有代码可以从一对看起来正确的 CustomValidators 中调用:
<asp:CustomValidator ID="cvtxt_pat_id" runat="server"
OnServerValidate="txt_pat_idValidate" ControlToValidate="txt_pat_id"
ErrorMessage="Text must be 8 or more characters." Display="Dynamic"/>
protected void txt_pat_idValidate(object sender, ServerValidateEventArgs e)
{
if (ddl_addl_pat_info.SelectedValue.ToString() == "2")
{
e.IsValid = (e.Value.Length > 1);
}
else
{
e.IsValid = true;
}
}
<asp:CustomValidator ID="cvtxt_pat_id" runat="server"
OnServerValidate="addresspartsValidate" ControlToValidate="txt_city"
ErrorMessage="Complete address must be entered." Display="Dynamic"/>
protected void addresspartsValidate(object sender, ServerValidateEventArgs e)
{
if (txt_pat_address.Text.Length > 1)
{
e.IsValid = (e.Value.Length > 1);
}
else
{
e.IsValid = true;
}
}
但据我了解,如果我正在测试的文本框为空,则该框永远不会验证,因此如果它们为空则不会触发这些文本框,这使得检查必填字段变得困难。那么……想法?
此外,关于我是否需要同时拥有客户端和服务器版本的测试,我得到了相互矛盾的说法。也许它在旧版本中是必需的,但现在不需要了?
最佳答案
你得往后想一点。您的自定义验证器应该在应该显示错误的项目上(特定文本框)。文本框上的自定义验证器应检查下拉列表以查看下拉列表是否具有触发文本框所需条件所需的特定条件。如果发现为真,那么您要检查文本框是否有输入并相应地返回 args.IsValid。
protected void cvTimeOfDay_ServerValidate(object source, ServerValidateEventArgs args)
{
if(ddlTimeOfDay.SelectedValue == "1" && txtbAddress.Text.Length == 0)
args.IsValid = false;
else
args.IsValid = true;
}
var MyValidation = {
DropdownValidation: function (sender, eventArgs) {
var isValid;
if (eventArgs && $('#ddlTimeOfDay').val() == '1') {
isValid = false;
}
else
isValid = true;
eventArgs.IsValid = isValid; }
}
<asp:DropDownList ID="ddlTimeOfDay" runat="server" ClientIDMode="Static">
<asp:ListItem Text="-Select-" Value="0"></asp:ListItem>
<asp:ListItem Text="PM" Value="1"></asp:ListItem>
<asp:ListItem Text="AM" Value="2"></asp:ListItem>
</asp:DropDownList>
<br />
<asp:TextBox Text="" ID="txtbAddress" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:CustomValidator ID="cvTimeOfDay" runat="server"
ErrorMessage="MustSelectValue"
ClientValidationFunction="MyValidation.DropdownValidation"
ControlToValidate="txtbAddress" ValidationGroup="group1"
onservervalidate="cvTimeOfDay_ServerValidate" ValidateEmptyText="true"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="group1"/>
要使用自定义验证器验证空白文本框,您需要将 ValidateEmptyText 属性设置为“true”。
如果您的网站不能确保已启用 JavaScript 以使用该页面,通常可以接受同时使用两者。有些浏览器可以关闭 JavaScript;如果 JavaScript 被关闭,它会绕过您的验证。使用客户端验证很好,因为它不会每次都回发来验证输入,而是在客户端上执行。
关于c# - 基于其他字段的条件验证,c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5518863/