ASP.NET 验证器 - 在第一次失败时停止验证

发布于 2024-08-14 12:19:05 字数 343 浏览 2 评论 0原文

如果发现先前的验证器在控制级别无效,是否有一种方法可以阻止验证器被评估?

例如,如果我创建一个包含 RequiredFieldValidatorRegularExpressionValidator 和自定义验证器的文本框,如果 RequiredFieldValidatorRegularExpressionValidator 已确定输入无效。

具体来说,在这种情况下,自定义验证器没有客户端支持,但如果没有输入数据(使用 RequiredFieldValidator),我想阻止回发,而不是进行回发。

Is there a method to stop validators from being evaluated if a previous validator is found to be not valid - at a control level?

For example, if I create a text box with a RequiredFieldValidator, a RegularExpressionValidator and a custom validator, I do not want the custom validator to be evaluated if the RequiredFieldValidator or RegularExpressionValidator have already determined that the input is invalid.

Specifically, in this case, the custom validator does not have client side support, but I would like to prevent the postback if no data is entered (using the RequiredFieldValidator) rather than having the postback take place.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江湖彼岸 2024-08-21 12:19:05

RegularExpressionValidatorRequiredFieldValidator 如果文本框为空,则返回 true 。换句话说:默认情况下,它们不会验证空文本框,因此您正在做正确的事情,并且它应该按预期开箱即用。

默认情况下,RequiredFieldValidator 和 RegularExpressionValidator 还将使用 JavaScript 验证客户端,因此如果它们中的任何一个失败,都不会发生回发。

请记住在客户端和服务器端测试您的正则表达式字符串,因为 JavaScript 和 .NET 正则表达式不是 100% 兼容。

定义 ValidationGroup 是一种很好的做法 所有控件,包括应触发验证的按钮。这应该启用服务器端验证,但我不是 100% 确定,因此,如果您的 CustomValidator 未触发,请添加以下代码作为 myButton_Click 方法的第一行:

myButton_Click(object Sender, EventArgs e)
{
    Page.Validate("MyValidationGroup");
    if (!Page.IsValid)
    {
        return;
    }

    // ...
}

Page.Validate() 接受validationGroup 作为参数。

Both RegularExpressionValidator and RequiredFieldValidator returns true if the text box is empty. In other words: They are by default not validating empty your empty text box, so with you are doing the correct thing and it should work as expected out of the box.

The RequiredFieldValidator and the RegularExpressionValidator will by default also validate client side - using JavaScript - so no postback will occur if either of them fails.

Remember to test your regular expression string both client side and server side, since JavaScript and .NET regex'es are not 100 % compatible.

It is a good practice to define ValidationGroup on all your controls, including the buttons that should trigger the validation. This should enable server side validation, but I am not 100 % sure, so if your CustomValidator is not triggeren add the following code as the first lines of your myButton_Click method:

myButton_Click(object Sender, EventArgs e)
{
    Page.Validate("MyValidationGroup");
    if (!Page.IsValid)
    {
        return;
    }

    // ...
}

Page.Validate() accepts a validationGroup as parameter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文