ASP.NET自定义验证器的排序以及Validator';s Text和ErrorMessage属性
本文关键字:Text 属性 ErrorMessage Validator 验证 自定义 NET 排序 ASP | 更新日期: 2023-09-27 18:29:06
我有一个带有两个验证器的TextBox
。第一个验证器检查TextBox
是否为空。第二个验证器检查TextBox
的值是否包含空格。但是,当我运行该项目并尝试在TextBox
中不使用任何文本进行验证时,它会显示两个验证器的错误消息。我想要的是,在第一个验证器成功验证之前,它不应该执行第二个验证器。
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox3" ErrorMessage="Please enter some value." Font-Names="Segoe UI" OnServerValidate="CustomValidator1_ServerValidate" SetFocusOnError="True"></asp:CustomValidator>
<br />
<asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="TextBox3" ErrorMessage="Spaces are not allowed." Font-Names="Segoe UI" OnServerValidate="CustomValidator2_ServerValidate" SetFocusOnError="True"></asp:CustomValidator>
<br />
所以我的问题是:
如何对验证进行排序,以便在成功验证另一个验证后调用一个验证?
我想问的另一个问题是,Validator的Text和ErrorMessage属性之间有什么区别?
您应该对空文本使用RequiredFieldValidator
,然后使用CustomValidator
来检查字符串组成。
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
ControlToValidate="TextBox3"
runat="server"
ErrorMessage="Please enter some value.">
</asp:RequiredFieldValidator>
<br />
<asp:CustomValidator
ID="CustomValidator2"
runat="server"
ControlToValidate="TextBox3"
ErrorMessage="Spaces are not allowed."
Font-Names="Segoe UI"
OnServerValidate="CustomValidator2_ServerValidate" SetFocusOnError="True">
</asp:CustomValidator>
<br />
来自MSDN的错误消息:
获取或设置在验证失败时的ValidationSummary控件。
MSDN中的文本:
获取或设置当验证失败。(覆盖标签。文本。)
编辑:
假设您正在进行多个验证,那么您应该为此使用单个CustomValidator
。在服务器端,您应该同时检查Empty和String composition,如下所示:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (string.IsNullOrEmpty(args.Value))
{
args.IsValid = false;
((CustomValidator)source).Text = "Please enter some value.";
}
else if (/*Check if has empty space*/)
{
args.IsValid = false;
((CustomValidator)source).Text = "Spaces are not allowed.";
}
else
{
args.IsValid = true;
}
}
问题答案:How can I sequence the validations so that one validation should be called after other is validated successfully ?
在.aspx页面中添加的验证器,将按照创建它们的相同顺序添加到Page.Validators
集合中。验证按Page.Validators集合中的顺序运行。因此,aspx文件中的第一个验证器位于Page.Validators中的第一位。如果你想重新排列顺序,那么正确的方法是按照你希望它们激发的顺序排列页面中的验证器。
注意:验证器将逐个启动。如果你不想启动下一个验证器,你可以使用Javascript来禁用下一个。调用第一个验证器中的ClientValidation函数
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="TextBox3"
ClientValidationFunction="disableNextVal" ....
//示例JavaScript代码
function disableNextVal()
{
// firstly check here for first condition, if First condition fails,
// disable the next validator as below.
var nextCustomVal = document.getElementById('nextCustomValidatorClientID');
ValidatorEnable(myVal, false);
// or use this one:
myVal.enabled = false;
}
//同样看到您的需求,似乎还有一种可能性是MaskValidator。请在此处查看。
2nd question:
CCD_ 10&ErrorMessage
属性:
Text
:验证失败时显示的消息。它通常出现在控件旁边,比如TextBox。它与ValidationSummary
控件无关。
ErrorMessage
:验证失败时显示在ValidationSummary
控件中的文本。如果您没有在上面设置Text
属性,则此ErrorMessage
值将显示在验证控件中。
虽然策略略有不同,但ValidationSummary可能对您有所帮助。