简体   繁体   中英

Email address validation on KeyReleased event in java

I'm having a java form where user has to insert his/her email address. And I want to validate that email address on keyreleased event. If the format is wrong then a message should be displayed saying the format is wrong and if the address is ok another message should be displayed saying format is correct.

This is the code of emailvalidator class file, I wrote to validate my email address.

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);
    }

    public boolean validate(final String hex) {

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

    }
}  

Now I want to use this to validate my email address field which is on userForum.java. And how can I use above validation class to validate my Email address on keyreleased event ?

(my textfield name is txt_email and message going to display on lbl_msg label.)

Use a DocumentListener on the underlying document as described here:

Value Change Listener to JTextField

Using a KeyListener instead means that if a user pastes in the email address, it won't be validated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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