Showing posts with label VBScript Regular expression. Show all posts
Showing posts with label VBScript Regular expression. Show all posts

Sunday, 22 September 2013

Validate email with Regxp (regular expression) in Visual Basic 6.0

option explicit
private Function IsValidEmail(ByVal emailStr As String) As Boolean
   
    ' if email is blank then return
    If VBA.Len(VBA.Trim$(emailStr)) = 0 Then
        IsValidEmail = False
        Exit Function
    End If
  
   
    Dim regex  As  Object
    Dim cMatch  As  Object ' For MatchCollection

    Set regex = CreateObject("VBScript.RegExp")  ' Object created with VBscript.RegExp class.

    regex.MultiLine = False ' email is a single line expression therefore multiline is set to false

    regex.IgnoreCase = False  ' Case sensitive checking is set to true

    regex.Pattern = "\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b" ' regular expression pattern

    Set cMatch = regex.Execute(emailStr)
   
    IsValidEmail = Not (cMatch.Count = 0) ' If no matches found then email is invalid

    ' first item of  collection cMatch return length of the email is it is not equal to the length of meail email is invalid.
    If IsValidEmail Then IsValidEmail = IIf(VBA.Len(cMatch.Item(0)) = VBA.Len(emailStr), True, False)
    'Release memory
    Set cMatch = Nothing
    Set regex = Nothing
End Function

Private sub Form_Load()
    if not IsValidEmail("subhroneelganguly@gmail.com")  then
        msgbox "Email not valid"
   else
      msgbox "Email valid"
    end if
End Sub