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.
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.
Fully customizable CRM Software for Freelancers and Small Businesses