Validate Email address in Java


The Email address can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the E-mail and the given input Email and returns true if they match and false otherwise.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {
   static boolean isValid(String email) {
      String regex = "^[\w-_\.+]*[\w-_\.]\@([\w]+\.)+[\w]+[\w]$";
      return email.matches(regex);
   }
   public static void main(String[] args) {
      String email = "john123@gmail.com";
      System.out.println("The E-mail ID is: " + email);
      System.out.println("Is the above E-mail ID valid? " + isValid(email));
   }
}

Output

The E-mail ID is: john123@gmail.com
Is the above E-mail ID valid? true

Now let us understand the above program.

In the main() method, The Email ID is printed. Then the isValid() method is called to validate the Email ID. A code snippet which demonstrates this is as follows:

public static void main(String[] args) {
   String email = "john123@gmail.com";
   System.out.println("The E-mail ID is: " + email);
   System.out.println("Is the above E-mail ID valid? " + isValid(email));
}

In the isValid() method, Pattern.matches() method matches the regular expression for the Email ID and the given input Email ID and the result is returned. A code snippet which demonstrates this is as follows:

static boolean isValid(String email) {
   String regex = "^[\w-_\.+]*[\w-_\.]\@([\w]+\.)+[\w]+[\w]$";
   return email.matches(regex);
}

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements