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;
    }
});
Mic
  • 49
  • 1
  • 6
  • 1
    As you only want digits, you might also want to look into using a [TextFormatter](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/TextFormatter.html) as [outlined in this answer](https://stackoverflow.com/questions/31458198/how-to-restrict-textfield-so-that-it-can-contain-only-one-character-javafx). – jewelsea Aug 17 '17 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}$"` –  Aug 17 '17 at 21:49
  • James_D why do you flag my question as duplicate? – Mic Aug 17 '17 at 21:50
  • sln - it still do not limit number of inputed digits – Mic Aug 17 '17 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. – James_D Aug 17 '17 at 22:26
  • @James_D It was my error - I have added two similar listeners to one textField and it didn't work. Thank you. – Mic Aug 19 '17 at 14:51

0 Answers0