我想在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
答案 0 :(得分:0)
在回发后,您能看到验证中的控件是否是完全相同的控件。我只是问过,因为控件是在Web表单的回发中从头开始重新创建的。您可能必须传入控件ID并在当前页面上搜索它(如果是这种情况(或类似的话))。