65.9K
CodeProject 正在变化。 阅读更多。
Home

自定义验证器和验证摘要

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (3投票s)

2007年10月10日

3分钟阅读

viewsIcon

72173

downloadIcon

463

一种在 CustomValidator 和 ValidationSummary 控件中根据不同条件显示自定义错误消息的解决方案。

Screenshot - CustomValidator_Validationsummary.jpg

引言

本文展示了如何构建自定义验证器,并根据不同的条件自定义错误消息,以及添加验证摘要控件并显示错误消息。如果您的表单很长,需要向下滚动才能点击提交按钮来验证整个表单,这将非常有用。如果验证摘要不显示错误消息,用户可能会感到困惑。默认情况下,自定义验证器控件不会将错误消息呈现到验证摘要控件。

背景

我正在处理一个冗长的表单,其中有各种自定义验证器,因为我们有需要根据用户选择进行不同验证的控件。在设计完表单后,我发现点击“提交”按钮后,我必须向上滚动才能检查错误消息。因此,我决定设计自己的自定义验证器,以根据选择显示错误消息。

Using the Code

如上图所示,我创建了一个示例项目,其中包含自定义验证器MyValidatorControl,我稍后将进行讨论。此页面执行以下操作:

  • 当您选中“>20,000.00”复选框并输入任何无效值时,它会显示错误消息“* >20000 required”
  • 当复选框未选中并且输入无效值(即负值或非数字值)时,它会显示错误消息“* >0 and <20000”
  • 错误消息同时显示在自定义验证控件和验证摘要中

我创建了一个 Web 自定义控件,并将其命名为 MyValidatorControl。我在程序集 MyValidatorControl.dll 中编译了它。 MyValidatorControl.dll 的源代码可在 MyValidatorControl.zip 中下载。

在函数 EvaluateIsValid() 中,根据复选框的选择验证 ControltoValidate 控件(在本例中为文本框)的值。属性 Text() 也返回不同的消息。

Public Class MyValidator
    Inherits CustomValidator
    Private sGT20 As String
    Private sLT20 As String
    Private bChked As Boolean = False
    Property Greaterthan20Text() As String
        Get
            Return sGT20
        End Get
        Set(ByVal value As String)
            sGT20 = value
        End Set
    End Property
    Property Lessthan20Text() As String
        Get
            Return sLT20
        End Get
        Set(ByVal value As String)
            sLT20 = value
        End Set
    End Property
    Property isGT20Checked() As Boolean
        Get
            Return ViewState("bChked")
        End Get
        Set(ByVal value As Boolean)
            ViewState("bChked") = value
        End Set
    End Property
    <Bindable(True), Category("Appearance"), _
        DefaultValue(""), Localizable(True)>_
        Overrides Property Text() As String
        Get
            If isGT20Checked Then
                Return Greaterthan20Text
            Else
                Return Lessthan20Text
            End If
        End Get
        Set(ByVal Value As String)
            If isGT20Checked Then
                Greaterthan20Text = Value
            Else
                Lessthan20Text = Value
            End If
        End Set
    End Property
    Protected Overrides Function EvaluateIsValid() As Boolean
        If Not IsNumeric(Me.GetControlValidationValue(_
            Me.ControlToValidate)) Then
            Return False
        End If
        If isGT20Checked And CInt(_
            Me.GetControlValidationValue(_
            Me.ControlToValidate)) < 20000 Then
            Return False
        ElseIf Not isGT20Checked And CInt(_
            Me.GetControlValidationValue(Me.ControlToValidate)) < 0 Then
            Return False
        End If
        Return True
    End Function
End Class

根据您的要求修改此代码并将其编译到程序集(DLL 文件)中。创建一个名为“Project1”的网站 - 或者您可以将其命名为任何您想要的名称 - 并将编译后的程序集添加到 Project1 的 bin 文件夹中。您可以将 DLL 复制并放置在 bin 文件夹中,也可以通过 Visual Studio 中的“添加引用”功能来完成。

在设计模式下打开 Default.aspx 并放置一个文本框、RequiredFieldValidator、一个复选框、一个 ValidationSummary 控件和自定义验证器 MyValidator。属性 Greaterthan20TextLessthan20Text 已为该控件预设。

<% @ Register Assembly="MyValidatorControl" 
    Namespace="MyValidatorControl" TagPrefix="cc1" %>

<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfvalidator" 
                runat="server" ErrorMessage="* Required" 
                ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
            <cc1:MyValidator id="MyValidator1" runat="server" 
                ControlToValidate="TextBox1" 
                ErrorMessage="* > 0" 
                Greaterthan20Text="* >20000 required" 
                Lessthan20Text="* >0 required and <20000 " 
                ClientValidationFunction="ValidateGT20Function" 
                ValidateEmptyText="True">
                    * >0 required and <20000 
            </cc1:MyValidator>
            <br/>
            <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" 
                Text="> 20,000.00" Width="98px" />
            <br/>
            <br/>
            <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
                ShowMessageBox="True" DisplayMode="List" 
                ShowSummary="false" />
            <asp:Button ID="Button1" runat="server" Text="Submit" />
        </div>
    </form>
</body>

复选框控件属性 AutoPostBack 应设置为 true。事件 CheckedChangedDefault.aspx.vb 中处理。

Protected Sub CheckBox1_CheckedChanged(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
    MyValidator1.isGT20Checked = CheckBox1.Checked
End Sub

MyValidator 控件具有一个名为 ClientValidationfunction 的属性,该属性设置为 ValidateGT20Function。这将是客户端 JavaScript 函数,用于检查文本框中的值并进行验证。

<script language="javascript" type="text/javascript">

function ValidateGT20Function(source, arguments)
{
    var val = 
        document.getElementById(document.getElementById(
        source.id).getAttribute("controltovalidate")).value;
    if (isNaN(val)) 
    {
        document.getElementById(source.id).setAttribute("errormessage",
            "* number required");
        arguments.IsValid = false;
    }
    else
    {
        if (document.getElementById("CheckBox1").getAttribute(
            "Checked") == true) 
        {
            if (val < 20000) 
            {
                document.getElementById(source.id).setAttribute(
                    "errormessage", "* >20000 required");
                arguments.IsValid = false;
            }
            else
            {
                arguments.IsValid = true;
            }
        }
        else
        {
            if (val < 0) 
            {
                document.getElementById(source.id).setAttribute(
                    "errormessage", "* >0 and <20000 required ");
                arguments.IsValid = false;
            } 
            else
            {
                arguments.IsValid = true;
            }
        }
    }
}

</script>

关注点

可能还有其他解决方案,但我找不到任何解决方案。请将任何其他可能解决方案的链接发送给我。祝您编程愉快!!并且不要忘记享受乐趣。

历史

  • 2007 年 10 月 10 日 -- 发布原始版本

许可证

本文档没有明确的许可证,但可能包含文章文本或下载文件本身的使用条款。如有疑问,请通过下方的讨论区联系作者。

作者可能使用的许可证列表可以在此处找到。

© . All rights reserved.