I'm trying to validate/filter my jtextbox wwith this Regex:


I want to filter two names with one space.

Tried using keytyped and keyreleased, but it just does not work (won't let me write anything on the textbox) and e.consume() does not work.

boolean StrCheck(String Exp,String str) {
            return Pattern.matches(Exp,str);

    public void keyTyped(KeyEvent e) {
        if (e.getSource() == jTextField) {
            String regexp = "^(([A-za-z]+[\s]{1}[A-za-z]+)|([A-Za-z]+))$";
            if (jTextField.getText().length() == 25) {
            } if (StrCheck(regexp,jTextField.getText())){

            }else {

I've been searching, but the only possible answer I got, was to create a Documentlistene BUT can't find any example or how actually do it and make it work.

1 Answers

George Z. On Best Solutions

Neither KeylListener, neither DocumentListener will work. In most of this kind of cases you would need to use a DocumentFilter. Before you do though, take a look on how to use formatted textfields. It might be enough for you. If it does not, this answer is what you are looking for.