Monday 22 May 2023

Email Validation in JTextField

I can provide you with an example code snippet in Java for email validation using a `JTextField`. Here's an example:


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.util.regex.*;


public class EmailValidationExample {

    private JFrame frame;

    private JTextField emailTextField;

    private JButton validateButton;


    public EmailValidationExample() {

        frame = new JFrame("Email Validation");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        

        emailTextField = new JTextField(20);

        validateButton = new JButton("Validate");

        validateButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                String email = emailTextField.getText();

                boolean isValid = validateEmail(email);

                if (isValid) {

                    JOptionPane.showMessageDialog(frame, "Email is valid!");

                } else {

                    JOptionPane.showMessageDialog(frame, "Invalid email!", "Error", JOptionPane.ERROR_MESSAGE);

                }

            }

        });


        JPanel panel = new JPanel();

        panel.add(emailTextField);

        panel.add(validateButton);


        frame.getContentPane().add(panel);

        frame.pack();

        frame.setVisible(true);

    }


    private boolean validateEmail(String email) {

        String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(email);

        return matcher.matches();

    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                new EmailValidationExample();

            }

        });

    }

}



In this example, we create a simple Swing GUI with a `JTextField` for entering the email and a `JButton` to validate it. When the "Validate" button is clicked, the email entered in the text field is passed to the `validateEmail` method.


The `validateEmail` method uses a regular expression pattern to check if the email is valid. The regular expression pattern `^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$` ensures that the email follows a specific format.


If the email is valid, a message dialog is displayed with the message "Email is valid!". Otherwise, an error message dialog is displayed with the message "Invalid email!".


You can run this code to see the email validation in action.

No comments:

Post a Comment

Cryptography API

Java offers a comprehensive set of cryptographic functionalities through its `java.security` package. This package provides various classes ...