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 implementing the Project.

Note. All the code used during the article is attached to the article in the 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: The local part of the email address is like the name of the user.
  • Sign @: The sign of the @ is an important part of any email address, if any email address is typed without a @ sign this is an incorrect email address.
  • Domain Name: The domain 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 does 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 the email address is incorrect and login to Gmail can not be completed.

Let's see an example of the 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.

 NetBeans

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".

Email Validation

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.

import java.util.regex.Pattern;

public class EmailValidation {
    
    public static boolean isValid(String email) {
        String emailFormat = "^[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+(?:\\."
                + "[a-zA-Z0-9_!#$%&'*+/=?`{|}~^-]+)*@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$";
        
        Pattern p = Pattern.compile(emailFormat);
        if (email == null) {
            return false;
        }
        return p.matcher(email).matches();
    }
    
    public static void main(String[] args) {
        EmailGui frame = new EmailGui();
        frame.setVisible(true);
    }      
}

Explanation

In the above code example first, we create a method named "isValid" In this method we define the format of the email address. Then create an object of Pattern class for compiling the format of the email, and then use an "if-else statement" that if the email is null then the output will be null, but if the compiler finds 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.

GUI

Explanation

In the above GUI, we create a "Label" for printing a heading a second "Label" for printing a message for the user that "Enter Your Email", and 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.

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author SYSADMIN
 */
public class EmailGui extends javax.swing.JFrame {

    /**
     * Creates new form EmailGui
     */
    public EmailGui() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea3 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        checkButton = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        finalResult = new javax.swing.JTextArea();
        inputEmail = new javax.swing.JTextField();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jTextArea3.setColumns(20);
        jTextArea3.setRows(5);
        jScrollPane3.setViewportView(jTextArea3);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("EmailValid");

        jLabel2.setText("Enter Your Email");

        checkButton.setText("Check");
        checkButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                checkButtonMouseClicked(evt);
            }
        });

        finalResult.setColumns(20);
        finalResult.setRows(5);
        jScrollPane4.setViewportView(finalResult);

        inputEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputEmailActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(105, 105, 105)
                        .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(104, 104, 104)
                        .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(18, 18, 18)
                        .addComponent(inputEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(107, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            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(31, 31, 31)
                .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(61, 61, 61)
                .addComponent(checkButton)
                .addGap(30, 30, 30)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void inputEmailActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }                                          

    private void checkButtonMouseClicked(java.awt.event.MouseEvent evt) {                                          
        boolean check = EmailValidation.isValid(inputEmail.getText());
        if (check) {
            finalResult.setText("Email is Valid");
        } else {
            finalResult.setText("Email is not Valid");
        }
    }                                         

    /**
     * @param args the command-line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EmailGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EmailGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EmailGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EmailGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new EmailGui().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton checkButton;
    private javax.swing.JTextArea finalResult;
    private javax.swing.JTextField inputEmail;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea3;
    // End of variables declaration                   
}

Explanation

We created 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.

EmailGui.java

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 text field below the button.

 Text Field

Explanation

In the above image, we enter an email address that is not valid according to the email format, so when we click on the check button the message "Email is not Valid" is printed into the text field.

 Email is not Valid

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.


Similar Articles