The task involves two stages:
- You must first create a text box that accepts digits only (up to 11 maximum).
- Second, you have to customize the user input according to your criteria (8 or 11 digits)
TextFormatter is used to solve the problem. A UnaryOperator must be passed to it to filter user input only by numbers and StringConverter to validate user input.
This is an example implementation:
UnaryOperator<TextFormatter.Change> filter = change -> {
if(change.getControlNewText().matches("\\d{0,11}")) {
return change;
}
return null;
};
StringConverter<String> converter = new StringConverter<String>() {
@Override
public String toString(String s) {
if(s == null || s.isBlank()) return "";
if(s.matches("\\d{8}|\\d{11}")) {
return s;
}
return "";
}
@Override
public String fromString(String s) {
if(s == null || s.isBlank()) return "";
if(s.matches("\\d{8}|\\d{11}")) {
return s;
}
throw new RuntimeException("Converter error");
}
};
textField.setTextFormatter(new TextFormatter<>(converter, null, filter));