I want to add validation in javafx TextField such that user should only be able to insert integer values ([0-9] and Dot ). Also user should be able to insert either B or b(for B
I created the following class to filter input on TextField
, which also uses the TextFormatter
introduced in JavaFX 8.
public class TextFieldValidator {
private static final String CURRENCY_SYMBOL = DecimalFormatSymbols.getInstance().getCurrencySymbol();
private static final char DECIMAL_SEPARATOR = DecimalFormatSymbols.getInstance().getDecimalSeparator();
private final Pattern INPUT_PATTERN;
public TextFieldValidator(@NamedArg("modus") ValidationModus modus, @NamedArg("maxCountOf") int maxCountOf) {
this(modus.createPattern(maxCountOf));
}
public TextFieldValidator(@NamedArg("regex") String regex){
this(Pattern.compile(regex));
}
public TextFieldValidator(Pattern pattern){
INPUT_PATTERN = pattern;
}
public static TextFieldValidator maxFractionDigits(int maxCountOf) {
return new TextFieldValidator(maxFractionPattern(maxCountOf));
}
public static TextFieldValidator maxIntegers(int maxCountOf) {
return new TextFieldValidator(maxIntegerPattern(maxCountOf));
}
public static TextFieldValidator integersOnly() {
return new TextFieldValidator(integersOnlyPattern());
}
public TextFormatter
You can use it like this:
textField.setTextFormatter(new TextFieldValidator(ValidationModus.MAX_INTEGERS, 4).getFormatter());
or you can instantiate it in a fxml file, and apply it to a customTextField with the according properties.
app.fxml:
CustomTextField:
public class CustomTextField {
private TextField textField;
public CustomTextField(@NamedArg("validator") TextFieldValidator validator) {
this();
textField.setTextFormatter(validator.getFormatter());
}
}
For your usecase you could call the TextFieldValidor constructor with the appropriate regex pattern and add the filter of James-D's answer to validateChange(Change c)