0

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

  • What do you mean by a `keyup event`? – Yahya May 19 '17 at 17:28
  • I meant, when the user typing, it will automatically validate email address and display the message –  May 19 '17 at 17:31
  • Are you using `JavaFX` or `Swing`? – Yahya May 19 '17 at 17:32
  • i'm using swing –  May 19 '17 at 17:33
  • Possible duplicate of [Value Change Listener to JTextField](http://stackoverflow.com/questions/3953208/value-change-listener-to-jtextfield) – Yahya May 19 '17 at 17:37
  • nope, couldn't find the solution there. and i'm sorry it should be key released event. I will edit the question again. –  May 19 '17 at 17:41
  • 3
    Do not use KeyListener for this; use a DocumentListener. Also, be aware that the syntax of an e-mail address is considerably more complicated than what your regular expression covers. – VGR May 20 '17 at 01:08

1 Answers1

0

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.

Community
  • 1
  • 1
Sam
  • 670
  • 1
  • 6
  • 20