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; } });
{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}$"