Email validation in Java using OWASP standards

Hello friends,

If you are building an application with form inputs, you may come across scenarios where you might be required to validate the email entered by the user.

In this post, let me share an easy way to do email validation.



Depending on your use case, you can start email validation in the most basic way. 

  1. First, you can do a simple check if the "@" character is present in your email or not.
  2. If you want to add more complexity to the validation, you may compare it against a regex with the "@" and "." characters.
  3. Similarly, you can add validation to compare it against special characters as well to try out various scenarios of users trying to enter an invalid email.
In this post, we will use the regex pattern used by OWASP validation.


Java Code:

import java.util.regex.Matcher; 

import java.util.regex.Pattern; 

 public class MainClass { 

     private static final String regex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"; 


 public static void main(String[] args) { 

 String email = "lewis@gmail.com."; 

 // initialize the Pattern object 

 Pattern pattern = Pattern.compile(regex); 

 // initialize the Matcher object 

 Matcher matcher = pattern.matcher(email); 

 System.out.println("Is the given Email Valid? " + matcher.matches()); 

 } 

}

 


Output:

Is the given Email Valid? false


Hope you found this code useful for your email validation needs. One thing to remember, though this regex uses the pattern given as per OWASP standard which covers almost most of the use cases. But still, it may not guarantee perfect validation for every scenario. 

Post a Comment

0 Comments