[英]asp.net required field validator for at least one textbox contains text
我在asp.net webform上有三个文本框,我是如何/可以使用必需的字段验证器来确保其中至少有一个包含文本?
我会像这样使用CustomFieldValidator:
<asp:CustomValidator runat="server"
ID="MyCustomValidator"
ValidationGroup="YOUR_VALIDATION_GROUP_NAME"
OnServerValidate="MyCustomValidator_ServerValidate"
ErrorMessage="At least one textbox needs to be filled in." />
然后在你的代码隐藏中你有:
protected void MyCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
if (/* one of three textboxes has text*/)
args.IsValid = true;
else
args.IsValid = false;
}
您还可以向此验证添加客户端组件,并通过使用AJAX工具包的ValidatorCalloutExtender控件扩展它来使其性感。
我不认为RequiredFieldValidator符合您的要求。 我会使用分配给您的任何字段的CustomValidator
,并在它触发时手动检查它们。
<script>
function doCustomValidate(source, args) {
args.IsValid = false;
if (document.getElementById('<% =TextBox1.ClientID %>').value.length > 0) {
args.IsValid = true;
}
if (document.getElementById('<% =TextBox2.ClientID %>').value.length > 0) {
args.IsValid = true;
}
if (document.getElementById('<% =TextBox3.ClientID %>').value.length > 0) {
args.IsValid = true;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="have to fill at least 1 field"
ControlToValidate="TextBox1"
ClientValidationFunction="doCustomValidate"
ValidateEmptyText="true" ></asp:CustomValidator><br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
不要忘记设置ValidateEmptyText="true"
因为默认设置是跳过空字段。 确保您也创建了类似的服务器端验证方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.