Validate Email Address in Java
In this Java core tutorial, we learn how to use the regular expression in Java to check whether an email address is valid or not.
Implement EmailUtils class
At this step we implement a new class named EmailUtils with a static method isValidEmail() to validate email address String. The method expects an email address String as augment and returns boolean value whether the email address is valid or not.
EmailUtils.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class EmailUtils {
private static final String EMAIL_REGEX = "^[a-zA-Z][a-zA-Z0-9._-]*\\@\\w+(\\.)*\\w+\\.\\w+$";
private static final Pattern emailPattern = Pattern.compile(EMAIL_REGEX);
public static boolean isValidEmail(String email) {
Matcher matcher = emailPattern.matcher(email);
return matcher.matches();
}
}
Using isValidEmail() method to check email addresses
In the following Java example program, we use the EmailUtils class above to check the differ valid and invalid email addresses.
CheckValidEmailExample.java
public class CheckValidEmailExample {
public static void main(String... args) {
// valid emails
System.out.println(EmailUtils.isValidEmail("test@simplesolution.com"));
System.out.println(EmailUtils.isValidEmail("abc.xyz@simplesolution.com"));
System.out.println(EmailUtils.isValidEmail("abc_xyz@simplesolution.com"));
System.out.println(EmailUtils.isValidEmail("user@simplesolution.dev"));
// invalid emails
System.out.println(EmailUtils.isValidEmail("usersimplesolution.dev"));
System.out.println(EmailUtils.isValidEmail("user@simplesolutiondev"));
}
}
true
true
true
true
false
false
Happy Coding 😊