How To Validate An Email Address In Java

Introduction

 
In this article, we will learn about the validation of email addresses in the Java Programming language. We will use NetBeans IDE for writing the code and implement the Project.
 
Note
All the code used during the article is attached with the article in form of a zip file. You can find the zip file at the top of the article.
 

Email Validation in Java

 
Email Validation is an important and common part of any application for registration and login to the application.
 
An Email address has three parts:
  • Local Part- local part of the email address is like the name of the user.
  • Sign @-  Sign of the @ is an important part of any email address, if any email address is typed without @ sign this is an incorrect email address.
  • Domain Name- Doman name is an identifier string that identifies the internet as a domain of administrative autonomy and authority. In networking contexts, and for application-specific naming and addressing purposes, domain names are used.
Note
Nowadays, when a user downloads any application in Android or IOS the Application needs to register with a user name, email address, password with some other information of the user. When we provide this information to the application the registration is complete if the user did not provide the required information the registration can not be done.
 
For example, when we download the Gmail application on any device, if we have an email id then we will provide that email id to the application. The application will verify that email address. If it exists, the device will ask about the password, but if our email address does not exist an error will show to the user that email address is incorrect and login to Gmail can not be completed.
 
Let's see an example of validation of an email address in Java Programming. For this example, we will use Netbeans IDE.
 
Step 1
 
First, we will create a project in NetBeans IDE named "EmailValidation". Let's start with an example.
 
Image 1
 
Explanation
 
When we open the NetBeans IDE for the project the first page will look like this. We will click on the "Next" button. 
 
Step 2
 
When we click on the "Next" button the next we will provide the name of the project "EmailValidation"
 
Image 2
 
Explanation
 
In the above image, we create the project named "MailValidation" and click on the "Finish" button.
 
Step 3
 
Now in our project, we will create the main Java class file named "EmailValidation.java". The code of this file is listed below.
  1. import java.util.regex.Pattern;  
  2.           
  3.   
  4. public class EmailValidation {  
  5.   
  6.     public static boolean isValid(String email){  
  7.         String emailFormate ="^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\."  
  8.                 + "[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$";  
  9.           
  10.         Pattern p = Pattern.compile(emailFormate);  
  11.         if(email == null){  
  12.         return false;  
  13.         }   
  14.         return p.matcher(email).matches();  
  15.     }  
  16.     public static void main(String[] args) {  
  17.         EmailGui frame= new EmailGui();  
  18.         frame.setVisible(true);  
  19.     }      
Explanation
 
In the above code example first, we create a method named "isValid" in this method we define the formate of the email address. Then create an object of Pattern class for compiling the formate of the email, and then use "if-else statement" that if the email is null then the output will be null, but if the compiler fine the email.   
 
Step 4
 
Now we will create a JFrame form for the GUI(Graphical User Interface) Java class named "EmailGui.java".Let's see the design of the GUI of our Project.
 
Image3
 
Explanation
 
In the above GUI, we create a "Label" for printing a heading and the second "Label" for print a message for the user that "Enter Your Email", a "TextField" for entering the email by the user. Below the label we create a button named "Click" and at last we have a "TextArea". We create this GUI Form with the "drag and drop" technique.
 
Step 5
 
Now we will update the coding part of the GUI The code of this file is listed below:
  1. /* 
  2.  * To change this license header, choose License Headers in Project Properties. 
  3.  * To change this template file, choose Tools | Templates 
  4.  * and open the template in the editor. 
  5.  */  
  6.   
  7. /** 
  8.  * 
  9.  * @author SYSADMIN 
  10.  */  
  11. public class EmailGui extends javax.swing.JFrame {  
  12.   
  13.   /** 
  14.      * Creates new form EmailGui 
  15.      */  
  16.   public EmailGui() {  
  17.     initComponents();  
  18.   }  
  19.   
  20.   /** 
  21.      * This method is called from within the constructor to initialize the form. 
  22.      * WARNING: Do NOT modify this code. The content of this method is always 
  23.      * regenerated by the Form Editor. 
  24.      */  
  25.   @SuppressWarnings("unchecked")  
  26.   // <editor-fold defaultstate="collapsed" desc="Generated Code">                            
  27.   private void initComponents() {  
  28.   
  29.     jScrollPane1 = new javax.swing.JScrollPane();  
  30.     jTextArea1 = new javax.swing.JTextArea();  
  31.     jScrollPane3 = new javax.swing.JScrollPane();  
  32.     jTextArea3 = new javax.swing.JTextArea();  
  33.     jLabel1 = new javax.swing.JLabel();  
  34.     jLabel2 = new javax.swing.JLabel();  
  35.     checkButton = new javax.swing.JButton();  
  36.     jScrollPane4 = new javax.swing.JScrollPane();  
  37.     finalResult = new javax.swing.JTextArea();  
  38.     inputEmail = new javax.swing.JTextField();  
  39.   
  40.     jTextArea1.setColumns(20);  
  41.     jTextArea1.setRows(5);  
  42.     jScrollPane1.setViewportView(jTextArea1);  
  43.   
  44.     jTextArea3.setColumns(20);  
  45.     jTextArea3.setRows(5);  
  46.     jScrollPane3.setViewportView(jTextArea3);  
  47.   
  48.     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
  49.   
  50.     jLabel1.setFont(new java.awt.Font("Tahoma"118)); // NOI18N  
  51.     jLabel1.setText("EmailValid");  
  52.   
  53.     jLabel2.setText("Enter Your Email");  
  54.   
  55.     checkButton.setText("Check");  
  56.     checkButton.addMouseListener(new java.awt.event.MouseAdapter() {  
  57.       public void mouseClicked(java.awt.event.MouseEvent evt) {  
  58.         checkButtonMouseClicked(evt);  
  59.       }  
  60.     });  
  61.   
  62.     finalResult.setColumns(20);  
  63.     finalResult.setRows(5);  
  64.     jScrollPane4.setViewportView(finalResult);  
  65.   
  66.     inputEmail.addActionListener(new java.awt.event.ActionListener() {  
  67.       public void actionPerformed(java.awt.event.ActionEvent evt) {  
  68.         inputEmailActionPerformed(evt);  
  69.       }  
  70.     });  
  71.   
  72.     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());  
  73.     getContentPane().setLayout(layout);  
  74.     layout.setHorizontalGroup(  
  75.     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(105105105).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(checkButton, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))).addGroup(layout.createSequentialGroup().addGap(104104104).addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(181818).addComponent(inputEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))).addContainerGap(107, Short.MAX_VALUE)));  
  76.     layout.setVerticalGroup(  
  77.     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(313131).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(inputEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(616161).addComponent(checkButton).addGap(303030).addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));  
  78.   
  79.     pack();  
  80.   } // </editor-fold>                          
  81.   private void inputEmailActionPerformed(java.awt.event.ActionEvent evt) {  
  82.     // TODO add your handling code here:  
  83.   }  
  84.   
  85.   private void checkButtonMouseClicked(java.awt.event.MouseEvent evt) {  
  86.     boolean check = EmailValidation.isValid(inputEmail.getText());  
  87.     if (check) {  
  88.       finalResult.setText("Email is Valid");  
  89.     }  
  90.     else {  
  91.       finalResult.setText("Email is not Valid");  
  92.     }  
  93.   
  94.   }  
  95.   
  96.   /** 
  97.      * @param args the command-line arguments 
  98.      */  
  99.   public static void main(String args[]) {  
  100.     /* Set the Nimbus look and feel */  
  101.     //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">  
  102.     /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
  103.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html  
  104.          */  
  105.     try {  
  106.       for (javax.swing.UIManager.LookAndFeelInfo info: javax.swing.UIManager.getInstalledLookAndFeels()) {  
  107.         if ("Nimbus".equals(info.getName())) {  
  108.           javax.swing.UIManager.setLookAndFeel(info.getClassName());  
  109.           break;  
  110.         }  
  111.       }  
  112.     } catch(ClassNotFoundException ex) {  
  113.       java.util.logging.Logger.getLogger(EmailGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  114.     } catch(InstantiationException ex) {  
  115.       java.util.logging.Logger.getLogger(EmailGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  116.     } catch(IllegalAccessException ex) {  
  117.       java.util.logging.Logger.getLogger(EmailGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  118.     } catch(javax.swing.UnsupportedLookAndFeelException ex) {  
  119.       java.util.logging.Logger.getLogger(EmailGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
  120.     }  
  121.     //</editor-fold>  
  122.     /* Create and display the form */  
  123.     java.awt.EventQueue.invokeLater(new Runnable() {  
  124.       public void run() {  
  125.         new EmailGui().setVisible(true);  
  126.       }  
  127.     });  
  128.   }  
  129.   
  130.   // Variables declaration - do not modify                       
  131.   private javax.swing.JButton checkButton;  
  132.   private javax.swing.JTextArea finalResult;  
  133.   private javax.swing.JTextField inputEmail;  
  134.   private javax.swing.JLabel jLabel1;  
  135.   private javax.swing.JLabel jLabel2;  
  136.   private javax.swing.JScrollPane jScrollPane1;  
  137.   private javax.swing.JScrollPane jScrollPane3;  
  138.   private javax.swing.JScrollPane jScrollPane4;  
  139.   private javax.swing.JTextArea jTextArea1;  
  140.   private javax.swing.JTextArea jTextArea3;  
  141.   // End of variables declaration                     

Explanation
 
We create the GUI with the "drag and drop" technique, now we will update the "EmailGui.java" class. We will update the method "checkButtonMouseClicked(java.awt.event.MouseEvent evt)" when we click on the button this method will be executed. This method will check the email address which is entered by the user id valid or not. If the email address is valid then it will print the message "Email is valid" otherwise it will print the message "Email is not valid".
 
Step 6
 
Now we will run our "EmailValidation" Project. The above code of our project generates the following output.
 
Image4
 
Explanation
 
In the above image, when we will run our project the application will be open on the screen like this. Now we have to enter the email address here. After entering the email address, we will click on the button. The result will be printed in the textField below to the button.
 
Image5
 
Explanation
 
In the above image, we enter an email address that is not valid according to the email formate, so when we click on the check button the message "Email is not Valid" is printed into the textField.
 
 Image6
 
Explanation
 
In the above image, as we see we enter an email address that is valid according to the format of the email. So, when we click on the button the message "Email is Valid" into the textField.
 
Note
For running this project you guys have to download NetBeans IDE.
 

Summary

 
In this article, we learned about email validation in Java Programming with an example project.