1

我想在 VB.NET 和 ASP.NET 中创建一个很好的验证系统,开发人员只需要指定一行来验证他们的控件。我想出了一个系统,使用 lambda 表达式。所以基本上,用户会像这样添加他们的控件:

ValidationHandler.CurrentInstance.AddValidationRule(Function() txtFirstName.Text.Length > 0, txtFirstName)

这与 Windows 窗体应用程序完美配合。我在 ASP.NET 上尝试过,我遇到的问题是,在我第二次验证时,它仍然保持以前的值。因此,例如,我有一个加载时长度为 0 的文本框,它验证无效。但是,如果我更改它的长度并再次单击提交,它仍然会看到文本框的长度为 0。

在此处输入图像描述

在此处输入图像描述

这就是问题所在。

此外,这是 ValidationHandler 的代码:

Imports System.Text

Public Class ValidationHandler

    'This are the rules.
    Private ValidationRules As New Dictionary(Of Func(Of Boolean), Control)

    'This is the error string builder. This will be empty if there are no errors.
    Public ErrorMessage As String    

    'This allows us to access the class without having to instantiate it. (Singleton pattren).
    Public Shared Property CurrentInstance As New ValidationHandler 

    ''' <summary>
    ''' Adds a validation rule.
    ''' </summary>
    ''' <param name="Rule">
    ''' The rule. 
    ''' </param>
    ''' <param name="control">
    ''' The control that validation is being applied on.
    ''' </param>
    ''' <remarks></remarks>
    Public Sub AddValidationRule(ByRef Rule As Func(Of Boolean), Control As Control)    
        'Adds that rule to the dictionary.
        ValidationRules.Add(Rule, Control)    
    End Sub    

    ''' <summary>
    ''' This function does all validation on the controls. 
    ''' </summary>
    ''' <returns>True if there are no errors and false if there are.</returns>
    ''' <remarks></remarks>
    Public Function IsValid() As Boolean

        'Clears the error message string builder.
        ErrorMessage = ""

        'Validates each rule against the control.
        For Each rule In ValidationRules

            If rule.Key.Invoke Then    
                Dim str = "yay"    
            Else    
                'Gets the error message from the tag, if the tag is not empty. 
                ErrorMessage = ErrorMessage & ("- " & rule.Value.ID & " is invalid." & "</br>" & Environment.NewLine)    
            End If    
        Next

        'Checks if there are any errors. If there are, return false, else return true.
        If ErrorMessage.Length > 0 Then
            Return False
        Else
            Return True
        End If

    End Function

    'Makes the class unable to be instantiated.
    Private Sub New()       

    End Sub

    Public Sub Clean()    
        ValidationRules.Clear()    
    End Sub    
End Class
4

1 回答 1

0

您能否查看验证中的控件是否与回发后页面上的控件完全相同。我之所以问,是因为控件是在 Web 表单的回发中从头开始重新创建的。如果是这种情况(或类似情况),您可能必须传入控件 ID 并在当前页面上搜索它。

于 2013-05-30T10:54:35.313 回答