Java Program to Check a Given Email Address Is Valid or Not

Java Program to Check a Given Email Address Is Valid or Not

Java Program to Check a Given Email Address Is Valid or Not

// Java program to check a given Email address 
// is valid or not

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;

public class Main {
  public static boolean isValidEmail(String val) {
    String regex = "^[a-zA-Z0-9_+&*-]+(?:\\." +
      "[a-zA-Z0-9_+&*-]+)*@" +
      "(?:[a-zA-Z0-9-]+\\.)+[a-z" +
      "A-Z]{2,7}$";

    Pattern pattern = Pattern.compile(regex);
    if (val == null)
      return false;
    return pattern.matcher(val).matches();
  }

  public static void main(String[] args) {
    String email1 = "[email protected]";
    String email2 = "[email protected]@testmail.com";

    if (isValidEmail(email1) == true)
      System.out.println("Email is valid");
    else
      System.out.println("Email is not valid");

    if (isValidEmail(email2) == true)
      System.out.println("Email is valid");
    else
      System.out.println("Email is not valid");

  }
}
Email is valid
Email is not valid

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment