首页 > 解决方案 > Email validation issue

问题描述

I am trying to validate email address field. I did it using Regex and it works fine but the issue is

I have set e.cancel to True in validating event, due to which it doesn't allow user to change focus unless user enters a correct email-id, even this is not the problem but it wont even allow the user to close the window/form.

I mean if the user is trying to abort the complete transaction what is the need of him/her to enter valid email id.

Here is my code -

  Private Sub tbemail_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles tbemail.Validating

    Dim pattern As String = "^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z][a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$"


    Dim match As System.Text.RegularExpressions.Match = Regex.Match(tbemail.Text.Trim(), pattern, RegexOptions.IgnoreCase)
    If (match.Success) Then
    Else
        MessageBox.Show("Please enter a valid email id", "Checking")
        e.Cancel = True
    End If
End Sub

标签: vb.netvalidation

解决方案


您应该将Cancel按钮的CausesValidation属性设置为。这样,单击它不会引发事件,即使最后一个控件中的数据无效,您也可以关闭表单。这假定表单是通过调用显示的。FalseValidatingShowDialog


推荐阅读