How to validate a JTextField of email ID with a regex in swing code?

北城以北 提交于 2019-12-06 16:36:24
Vallabh Patade

I hope this will help. When you Click on Submit button on SWING UI, in actionListener write the validation code.

   Emailvalidator emailValidator = new Emailvalidator();
   if(!emailValidator.validate(emailField.getText().trim())) {
        System.out.print("Invalid Email ID");
        /*
           Action that you want to take. For ex. make email id field red
           or give message box saying invalid email id.
        */
   }

This is the seperate class EmailValidator

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmailValidator {

    private Pattern pattern;
    private Matcher matcher;

    private static final String EMAIL_PATTERN = 
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public EmailValidator() {
        pattern = Pattern.compile(EMAIL_PATTERN);
    }

    /**
     * Validate hex with regular expression
     * 
     * @param hex
     *            hex for validation
     * @return true valid hex, false invalid hex
     */
    public boolean validate(final String hex) {

        matcher = pattern.matcher(hex);
        return matcher.matches();

    }
}

On a side note, this will enable you that the entered email id is in the correct format. If you want to validate the id, send an email containing a confirmation no and ask the user to enter that number on your UI and then proceed.

The format of an e-mail address can get pretty complex. In fact, its complexity is almost legendary.

The InternetAddress class in JavaMail is a much more reliable way to parse an e-mail address than a regular expression.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!