VB.NET email validation with Regex
I've tried implementing a rather simple email validation function that seems return a false match even though the input is a valid email. I have searched for any issues with the existing regex but it seems to be correct.
Even though the match returns a false value the program is stepping to the next validation level (which it shouldn't).
Here is the email validation function.
Function EmailAddressChecker(ByVal emailAddress As String) As Boolean
Dim regExPattern As String = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$"
Dim emailAddressMatch As Match = Regex.Match(emailAddress, regExPattern)
If emailAddressMatch.Success Then
Return True
Else
Return False
End If
End Function
And for the form validation that calls upon the email validation function.
If (String.IsNullOrEmpty(EmailTextBox.Text) OrElse EmailAddressChecker(EmailTextBox.ToString)) Then
MessageBox.Show("Please enter a valid email addresss")
Return False
End If
The call for all of this happens on an click event which triggers a cascading serious of If statements checking to see if all the fields are set.
Skipping a large chunk of code the click event asks if "AreFieldsSet <> True". Inside of the "AreFieldsSet" function contains all the validation for multiple inputs; one of which is the email validation if statement.
Are the emails in UpperCase? If they aren't, they won't match.
If you want to modify the Regex so that it is Case insensitive, use this:
"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$"
要验证您需要使用Regex对象的IsMatch函数的电子邮件地址,它会评估输入的电子邮件地址是否有效。
Function EmailAddressChecker(ByVal emailAddress As String) As Boolean
Dim r As System.Text.RegularExpressions.Regex = Nothing
Dim regExPattern As String = "^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$"
If r.IsMatch(emailAddress ,regExPattern ) Then
Return True
Else
Return False
End If
End Function
您可以尝试此代码进行表单验证If (String.IsNullOrEmpty(EmailTextBox.Text) OrElse EmailAddressChecker(EmailTextBox.ToString)<>true) Then MessageBox.Show("Please enter a valid email addresss") Return False End If
上一篇: RegEx无法识别无效的电子邮件