- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Validate Email address in Java
The Email address can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the E-mail and the given input Email and returns true if they match and false otherwise.
A program that demonstrates this is given as follows:
Example
public class Demo { static boolean isValid(String email) { String regex = "^[\w-_\.+]*[\w-_\.]\@([\w]+\.)+[\w]+[\w]$"; return email.matches(regex); } public static void main(String[] args) { String email = "john123@gmail.com"; System.out.println("The E-mail ID is: " + email); System.out.println("Is the above E-mail ID valid? " + isValid(email)); } }
Output
The E-mail ID is: john123@gmail.com Is the above E-mail ID valid? true
Now let us understand the above program.
In the main() method, The Email ID is printed. Then the isValid() method is called to validate the Email ID. A code snippet which demonstrates this is as follows:
public static void main(String[] args) { String email = "john123@gmail.com"; System.out.println("The E-mail ID is: " + email); System.out.println("Is the above E-mail ID valid? " + isValid(email)); }
In the isValid() method, Pattern.matches() method matches the regular expression for the Email ID and the given input Email ID and the result is returned. A code snippet which demonstrates this is as follows:
static boolean isValid(String email) { String regex = "^[\w-_\.+]*[\w-_\.]\@([\w]+\.)+[\w]+[\w]$"; return email.matches(regex); }
Advertisements