HomeLanguagesJavaCheck if Email Address is Valid or not in Java

Check if Email Address is Valid or not in Java

Given a string, find if the given string is a valid email or not.

Input : email = "[email protected]"
Output : Yes

Input : email = "[email protected]"
Output : No
Explanation : There is an extra dot(.) before org.

Prerequisite: Regular Expressions in Java 

Regular Expressions 

Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java.util.regex package. 

In order to check that an email address is valid or not, we use the below-given regular expression provided in the OWASP Validation Regex repository.

^[a-zA-Z0-9_+&*-] + (?:\\.[a-zA-Z0-9_+&*-]
+ )*@(?:[a-zA-Z0-9-]+\\.) + [a-zA-Z]{2, 7}$ 

Code – 

Java




// Java program to check if an email address
// is valid using Regex.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;
  
class Test
{
    public static boolean isValid(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();
    }
  
    public static void main(String[] args)
    {
        ArrayList<String> address = new ArrayList<>();
            
          address.add("[email protected]");
          address.add("writing.geeksforgeeks.org");
            
        for(String i : address){
            if (isValid(i))
                System.out.println(i + " - Yes");
            else
                System.out.println(i + " - No");
        }
    }
}


Output

[email protected] - Yes
writing.geeksforgeeks.org - No

This article is contributed by Pranav. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the Lazyroar main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 

RELATED ARTICLES

4 COMMENTS

Most Popular

Dominic
32548 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6922 POSTS0 COMMENTS
Nicole Veronica
12039 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12144 POSTS0 COMMENTS
Shaida Kate Naidoo
7059 POSTS0 COMMENTS
Ted Musemwa
7300 POSTS0 COMMENTS
Thapelo Manthata
7016 POSTS0 COMMENTS
Umr Jansen
7005 POSTS0 COMMENTS