0

I need to limit input length to 4 digits in JFX textField (field can be empty or have value 0-9999). Below solution works only partially - I can input only digits , but as many as i want - limit do not work. Even if I remove {0,4} from regex and change IF condition to:

if(newText.matches("\d") && newText.length()>=0 && newText.length()<5)

it doesn't work too. Where is the error?

JFXtextField.textProperty().addListener((obs, oldText, newText) -> { if(newText.matches("\\d{0,4}")) { newText = newText; } else { newText = oldText; } }); 
6
  • 1
    As you only want digits, you might also want to look into using a TextFormatter as outlined in this answer. Commented Aug 17, 2017 at 21:14
  • {0,4} is a regex range quantifier, it greedily matches up to 4 digits, but it will also match no digits. Add anchors to constrain the match "^\\d{0,4}$" Commented Aug 17, 2017 at 21:49
  • James_D why do you flag my question as duplicate? Commented Aug 17, 2017 at 21:50
  • sln - it still do not limit number of inputed digits Commented Aug 17, 2017 at 21:54
  • @Mic Doesn't the same technique work for this? Surely it is exactly the same problem. I added some other questions to the list. Commented Aug 17, 2017 at 22:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.