2

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

^(([A-za-z]+[\s]{1}[A-za-z]+)|([A-Za-z]+))$

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

    @Override
    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) {
                e.consume();
            } if (StrCheck(regexp,jTextField.getText())){

            }else {
                e.consume();
            }

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.

jannowitz
  • 84
  • 7
FerGuy
  • 67
  • 7
  • For [example](https://stackoverflow.com/questions/28790820/jtextfield-with-regex-applied-wont-accept-value-until-after-the-document-is-app/28790963#28790963) and [example](https://stackoverflow.com/questions/25418243/data-validation-with-joptionpane/25418345#25418345) – MadProgrammer May 12 '19 at 09:25

1 Answers1

3

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.

George Z.
  • 6,643
  • 4
  • 27
  • 47
  • Hi, thanks for helping I tried using the PatternFilter, it works just don't let me add a White Space, maybe something wrong with my regex, I'll be using the formatted textfields in others jtextbox so thanks. – FerGuy May 12 '19 at 09:47