Email validation using regular expressions is a common task that may be required in any application accepting email addresses as required information in the registration step. There may be more usecases, but that’s not the point of discussion here.
Let’s directly jump into the main discussion i.e. to validate email in Java using regular expressions.
1. Simple Regex
Regex : ^(.+)@(.+)$
This one is simplest and only cares about ‘@’ symbol. Before and after ‘@’ symbol, there can be any number of characters. Let’s see a quick example to see what I mean.
This regex example uses all the characters permitted by RFC-5322, which governs the email message format. Some of the permitted characters present a security risk if passed directly from user input to an SQL statement, such as the single quote (‘) and the pipe character (|).
You should be sure to escape sensitive characters when inserting the email address into a string passed to another program to prevent security holes such as SQL injection attacks.
Both the local part and the domain name can contain one or more dots, but no two dots can appear right next to each other. Furthermore, the first and last characters in the local part and in the domain name must not be dots:
5. Restrict Char Length in Top-level Domain [Recommended]
Now let’s modify the regex such that the domain name must include at least one dot, and that the part of the domain name after the last dot can only consist of letters.
Let’s say domain names are like secondlevel.com or thirdlevel.secondlevel.com. The top-level domain (.com in these examples) must only consist of two to six letters.
This last regex is my recommendation for simple email validation in java. Please note that email validation in java without regular expression may be possible, but it is not recommended. Anywhere you need to deal with patterns, regular expressions are your friend.
Please feel free to use this regex as well as edit it as per your application’s additional needs.
Happy Learning !!
Comments
Subscribe
13 Comments
Most Voted
NewestOldest
Inline Feedbacks
View all comments
Lokesh Gupta
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments