在回发时,如何向验证摘要添加错误消息? [英] On postback, how can I add a error message to validation summary?

查看:28
本文介绍了在回发时,如何向验证摘要添加错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个问题:

在用户单击提交时回发时,如何向验证摘要添加错误消息?

On postback when a user clicks submit, how can I add a error message to validation summary?

是否也可以使用内置的 .net 验证控件突出显示特定文本框?

Is it also possible to highlight a particular textbox using the built in .net validation controls?

推荐答案

动态创建 CustomValidator 控件并将其直接添加到 Page.Validators 集合中.

Dynamically create a CustomValidator control and add it directly to the Page.Validators collection.

Dim err As New CustomValidator
err.ValidationGroup = "MyGroup"
err.IsValid = False
err.ErrorMessage = "The password is invalid"
Page.Validators.Add(err)

与向标记添加 CustomValidator 不同,此方法允许您根据服务器端业务逻辑添加任意数量的任意错误消息.

Unlike adding the CustomValidator to the markup, this method allows you to add any number of arbitrary error messages based on server-side business logic.

请注意,您也可以直接将其添加到页面中,但需要遵循一些规则:

Note that you can also add it to the page directly, but there are a couple of rules to follow:

  1. 您必须将控件添加到与验证组的控件相同的命名容器中.
  2. 如果您不希望验证消息出现在页面中的随机位置,您要么必须将验证器添加到特定容器,要么需要使用 CSS 类或样式来抑制它.

您还可以创建一个 自定义类并实现IValidator,可以用一行代码添加消息,但该方法不支持Validation Groups.

You can also create a custom class and implement IValidator, which enables you to add the message with one line of code, but this method doesn't support Validation Groups.

根据 Anders Fjeldstad 的建议,这里有一组方便的扩展方法.

Per Anders Fjeldstad's suggestion, here are a set of handy extension methods.

Imports Microsoft.VisualBasic
Imports System.Runtime.CompilerServices

Public Module PageExtensions

    <Extension()> _
    Public Sub AddValidationError(ByVal p As System.Web.UI.Page, ByVal errorMessage As String)
        p.AddValidationError(errorMessage, String.Empty)
    End Sub

    <Extension()> _
    Public Sub AddValidationError(ByVal p As System.Web.UI.Page, ByVal errorMessage As String, ByVal validationGroup As String)
        Dim err As New CustomValidator
        err.ValidationGroup = validationGroup
        err.ErrorMessage = errorMessage
        err.IsValid = False
        p.Validators.Add(err)
    End Sub

End Module

这篇关于在回发时,如何向验证摘要添加错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆