Android Code Snippet ✅ Validate a correctly formatted email address

SubName: Validate a users email address format using a regular expression.
Description: You can use the following code to validate that a user has entered a correctly formatted email address. Characters like "@ , > = .. etc" are checked and the email address format is validated via the regular expression. This is to verify that the email address conforms to the RFC 5322 standard internet message format.

It can be awkward typing on a mobile device keyboard, mistakes can easily happen. Being able to validate an email address format before it is sent is very important. I've been using this particular regular expression for years on clients e-commerce websites, online registration forms and enquiry forms. It works great in Android apps too.

I've just modified the regular expression to ignore case sensitivity, also updated to a function.
B4X:
Sub AppStart (Args() As String)
    Log("Valid email format = " & Validate_Email("[email protected]"))
End Sub

Sub Validate_Email(EmailAddress As String) As Boolean
    Dim MatchEmail As Matcher = Regex.Matcher("^(?i)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])$", EmailAddress)
 
    If MatchEmail.Find = True Then
        Log(MatchEmail.Match)
        Return True
    Else
        Log("Oops, please double check your email address...") 
        Return False
    End If
End Sub
Tags: validate email address, format, regex
 
Last edited:

DonManfred

Expert
Licensed User
Longtime User
B4X:
sub IsEmail(EmailAddress As String) as Boolean
  Dim MatchEmail As Matcher = Regex.Matcher("^(?i)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])$", EmailAddress)
  If MatchEmail.Find = True Then
    Log(MatchEmail.Match)
    'Do something
    return true
  Else
    Log("Oops, please double check your email address")
    return false
  End If
end sub
'
' Example
'
Dim EmailAddress As String = "[email protected]"
log(IsEmail(EMailAddress))
 
Last edited:
Top