I'm trying to validate the following from the text field: 1. It's not empty (has a value) 2. Is a number (not some other character) 3. Is with a certain min and max (range)
For this I use an empty validator, a regex validator and a predicate validator respectively and combine them. However it seems to only utilize the last validator in the list and ignores the others.
Here is the code:
private final Spinner<Integer> createSpinner(ValueRange range, int initialValue){
int min = (int) range.getMinimum();
int max = (int) range.getMaximum();
//TODO add validation in here
Spinner<Integer> spinner = new Spinner<Integer>();
spinner.setPrefSize(30, 30);
spinner.getStyleClass().add(Spinner.STYLE_CLASS_SPLIT_ARROWS_VERTICAL);
spinner.setEditable(true);
SpinnerValueFactory.IntegerSpinnerValueFactory valueFactory = new SpinnerValueFactory.IntegerSpinnerValueFactory(min, max, initialValue);
valueFactory.setConverter(new TimeIntegerStringConverter());
valueFactory.setWrapAround(true);
spinner.setValueFactory(valueFactory);
//validation
TextField editor = spinner.getEditor();
validationSupport.registerValidator(editor, false, Validator.<String>combine(
Validator.createEmptyValidator("Field cannot be empty",Severity.WARNING),
checkInRangeValidator(range),
checkIntegerValidator()
));
return spinner;
}
private static Validator<String> checkInRangeValidator(ValueRange range) {
String message = String.format("Input value must be between [%d,%d]", (int) range.getMinimum(), (int) range.getMaximum());
return Validator.<String>createPredicateValidator(
s -> range.isValidIntValue(Integer.valueOf(s)),
message,
Severity.ERROR
);
}
private static Validator<String> checkIntegerValidator(){
String message = "Input must be a number";
return Validator.createRegexValidator(message, "\\d+", Severity.ERROR);
}
I'm unsure why the validators are not combining. If I add them separately in the combine function each validator works. But together they don't.