ASP.NET WebForms: Short-circuit validation

2019-07-05 02:58发布

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:

  1. If required validation fails, show required's error message only.
  2. If isNumbers validation fails, show isNumber's error message only.
  3. If isNonNegative validation fails, show isNonNegative's error message only.
  4. If isLessThanMax validation fails, show isLessThanMax's error message only.

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.

Is there any way to "short-circuit" out of the validation to get my expected behavior?

1条回答
霸刀☆藐视天下
2楼-- · 2019-07-05 03:22

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>

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;
}
查看更多
登录 后发表回答