September 22, 2020
Estimated Post Reading Time ~

How to check valid and invalid email addresses using Java?

We will see how to validate and check whether the entered email ID is valid or not using Java programming. Here I am writing a simple Java code that will validate the format of email using regular expression(regex).

  1. Declare a variable with email addresses of type String[] array.
  2. Write a for loop which will iterate every item(email addresses) from your array.
  3. Create a parameterized method with return type boolean which will accept your email address and check for valid or not.
  4. Method will match the format of your email with regex: [a-zA-Z0-9._-][a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4} and return true or false.
package rashid.jorvee;
public class ValidEmailValidator {
public static void main(String[] args) {
  String[] emailAddresses= {"sohal@shopoo.co","adyu+@sud.com","asg_sj-@asgd.co","rashid@do.in.com","rashid.ta@rasj.com","fdh%sdfkj_@dsj.cojn"};
  for(String email : emailAddresses) {
   if(validEmail(email)) {
    System.out.println("Valid email address :" +email);
   }
   else {
    System.out.println("Invalid email address :"+email);
   }
  }
 }
 static boolean validEmail(String email) {
  return email.matches("[a-zA-Z0-9._-][a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}");
 }
}

Output:
Valid email address:vsohal@shopoo.co
Invalid email address:adyu+@sud.com
Valid email address:asg_sj-@asgd.co
Valid email address:rashid@rasj.com
Valid email address:rashid.ta@rasj.com
Invalid email address:fdh%sdfkj_@dsj.cojn


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.