Java Examples - Validate email address format

Advertisements


Problem Description:

How to validate an email address format?

Solution:

Following example demonstrates how to validate e-mail address using matches() method of String class.

public class Main {
   public static void main(String[] args) {
      String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\
      @([\\w]+\\.)+[\\w]+[\\w]$";
      String email1 = "user@domain.com";
      Boolean b = email1.matches(EMAIL_REGEX);
      System.out.println("is e-mail: "+email1+" :Valid = " + b);
      String email2 = "user^domain.co.in";
      b = email2.matches(EMAIL_REGEX);
      System.out.println("is e-mail: "+email2
      +" :Valid = " + b);
   }
}

Result:

The above code sample will produce the following result.

is e-mail: user@domain.com :Valid = true
is e-mail: user^domain.co.in :Valid = false


Advertisements
Advertisements