ASP.NET WebForms:短路验证 [英] ASP.NET WebForms: Short-circuit validation
问题描述
我有一个正在验证的网格文本框:
I have a grid text box that I am validating:
<telerik:RadTextBox ID="txtMerchMin" runat="server" Text='<%# Bind("MerchandiseMinimumAmount") %>'></telerik:RadTextBox>
<asp:RequiredFieldValidator ID="required" runat="server" ErrorMessage="* required" ControlToValidate="txtMerchMin"></asp:RequiredFieldValidator>
<asp:CompareValidator runat="server" ID="isNumbers" Type="Double" Operator="DataTypeCheck" ControlToValidate="txtMerchMin" ErrorMessage="* must be numeric" />
<asp:CompareValidator runat="server" ID="IsNonNegative" Type="Double" Operator="GreaterThanEqual" ControlToValidate="txtMerchMin" AmountToCompare="0" ErrorMessage="* should be non-negative"/>
<asp:CompareValidator ID="isLessThanMax" ControlToValidate="txtMerchMin" Type="Double" ControlToCompare="txtMerchMax" Operator="LessThan" Text="* should be less than max" runat="server"></asp:CompareValidator>
我希望验证按以下顺序运行并且行为如下:
I would like the validations to run in the following order and behave like so:
- 如果 required 验证失败,则仅显示 required 的错误消息.
- 如果 isNumbers 验证失败,则仅显示 isNumber 的错误消息.
- 如果 isNonNegative 验证失败,则仅显示 isNonNegative 的错误消息.
- 如果 isLessThanMax 验证失败,显示 isLessThanMax 的错误仅消息.
由于现在写的代码,当txtMerchMin中的值为非数字时,我同时看到isNumbers、isNonNegative和isLessThanMax的错误信息.
As the code is written right now, when the value in txtMerchMin is non-numbers, I see the error message of isNumbers, isNonNegative, and isLessThanMax all at the same time.
有什么方法可以短路"验证以获得我的预期行为?
推荐答案
只需制作一个在服务器端工作的 CustomValidator 并使用 if/else 语句来实现您的行为.例如:
Just make a CustomValidator that works on serverside and using if/else statements achieve your behaviour. For example:
<telerik:RadTextBox ID="txtMerchMin" runat="server" Text='<%# Bind("MerchandiseMinimumAmount") %>'></telerik:RadTextBox>
<asp:RequiredFieldValidator ID="required" runat="server" ErrorMessage="* required" ControlToValidate="txtMerchMin"></asp:RequiredFieldValidator>
<asp:CustomValidator runat="server" ID="customValidator" Display="Dynamic" SetFocusOnError="true" ControlToValidate="txtMerchMin"></asp:CustomValidator>
在 init
方法集后面的代码中(您也可以在标记中执行此操作)
In code behind in init
method set (you can do this also in markup)
customValidator.ServerValidate += new ServerValidateEventHandler(customValidator_ServerValidate);
然后在函数中实现你的逻辑:
And then in function implement your logic:
protected void customValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
bool isValid = true;
double price;
bool isDouble = Double.TryParse(args.Value, out price);
if(!isDouble) {
// not double (numeric)
isValid = false;
}
else if (...)
else if (...)
args.IsValid = isValid;
}
这篇关于ASP.NET WebForms:短路验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!