如何调用函数来验证已放入文本框的密码?
Function ValidatePassword(ByVal pwd As String,
Optional ByVal minLength As Integer = 8,
Optional ByVal numUpper As Integer = 2,
Optional ByVal numLower As Integer = 2,
Optional ByVal numNumbers As Integer = 2,
Optional ByVal numSpecial As Integer = 2) As Boolean
' Replace [A-Z] with \p{Lu}, to allow for Unicode uppercase letters.
Dim upper As New System.Text.RegularExpressions.Regex("[A-Z]")
Dim lower As New System.Text.RegularExpressions.Regex("[a-z]")
Dim number As New System.Text.RegularExpressions.Regex("[0-9]")
' Special is "none of the above".
Dim special As New System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]")
' Check the length.
If Len(pwd) < minLength Then Return False
' Check for minimum number of occurrences.
If upper.Matches(pwd).Count < numUpper Then Return False
If lower.Matches(pwd).Count < numLower Then Return False
If number.Matches(pwd).Count < numNumbers Then Return False
If special.Matches(pwd).Count < numSpecial Then Return False
' Passed all checks.
Return True
End Function
答案 0 :(得分:1)
要使用此功能,您需要从密码文本框中获取文本并将其放入函数中:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strPwd As String
strPwd = TextboxPassword.Text 'textbox containing password
If ValidatePassword(strPwd) = True Then
MessageBox.Show("Password is valid!")
Else
MessageBox.Show("Password is invalid. Please try again.")
End If
End Sub
Function ValidatePassword(ByVal pwd As String,
Optional ByVal minLength As Integer = 8,
Optional ByVal numUpper As Integer = 2,
Optional ByVal numLower As Integer = 2,
Optional ByVal numNumbers As Integer = 2,
Optional ByVal numSpecial As Integer = 2) As Boolean
' Replace [A-Z] with \p{Lu}, to allow for Unicode uppercase letters.
Dim upper As New System.Text.RegularExpressions.Regex("[A-Z]")
Dim lower As New System.Text.RegularExpressions.Regex("[a-z]")
Dim number As New System.Text.RegularExpressions.Regex("[0-9]")
' Special is "none of the above".
Dim special As New System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]")
' Check the length.
If Len(pwd) < minLength Then Return False
' Check for minimum number of occurrences.
If upper.Matches(pwd).Count < numUpper Then Return False
If lower.Matches(pwd).Count < numLower Then Return False
If number.Matches(pwd).Count < numNumbers Then Return False
If special.Matches(pwd).Count < numSpecial Then Return False
' Passed all checks.
Return True
End Function
请注意,其他参数是可选的。您只需要将密码文本放入函数中。当您单击Button1代码执行时,最终调用函数ValidatePassword,并发出一个消息框,告诉您密码是否有效。