简体   繁体   English

如何在Swing代码中使用正则表达式验证电子邮件ID的JTextField?

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

I have tried a lot for this validation but I'm not getting where to put the following code 我已经为此验证做了很多尝试,但是我没有把下面的代码放在哪里

String expression="^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";.

Please help me in this. 请帮助我。

I hope this will help. 我希望这将有所帮助。 When you Click on Submit button on SWING UI, in actionListener write the validation code. 当您单击SWING UI上的Submit按钮时,在actionListener中编写验证代码。

   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 这是单独的类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. 附带说明,这将使您输入的电子邮件ID格式正确。 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. 如果要验证ID,请发送一封包含确认号的电子邮件,并要求用户在您的UI中输入该数字,然后继续。

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. 与正则表达式相比, JavaMail中InternetAddress类是解析电子邮件地址的可靠得多的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM