Validate email address android
Validating an email address in Android can be done using regular expressions. Here's an example of how you can do it:
public boolean isValidEmail(String email) {
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\." +
"[a-zA-Z0-9_+&*-]+)*@" +
"(?:[a-zA-Z0-9-]+\\.)+[a-z" +
"A-Z]{2,7}$";
Pattern pat = Pattern.compile(emailRegex);
if (email == null)
return false;
return pat.matcher(email).matches();
}
You can use this method to validate an email address. It will return true
if the email is valid and false
otherwise.
Here's a breakdown of the regular expression used:
^
asserts the start of a line[a-zA-Z0-9_+&*-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers,_
,+
,&
,*
,-
(?:
starts a non-capturing group[a-zA-Z0-9_+&*-]+
matches one or more of the same characters as above)*
closes the non-capturing group and makes it optional (i.e., it can be repeated zero or more times)@
matches the@
symbol(?:
starts another non-capturing group[a-zA-Z0-9-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers,-
\\.
matches a period (escaped with a backslash because.
has a special meaning in regular expressions)[a-zA-Z]{2,7}
matches the domain extension (it must be between 2 and 7 characters long and can only contain letters)$
asserts the end of a line
You can use this method like this:
String email = "[email protected]";
if (isValidEmail(email)) {
Log.d("Email", "Email is valid");
} else {
Log.d("Email", "Email is not valid");
}
Remember that this is not foolproof and there are many ways to format an email address that this regular expression will not catch. For example, it will not catch email addresses with non-ASCII characters or email addresses with non-standard top-level domains.