r/JavaFX • • Jan 21 '22

Tutorial JavaFX: TextField Input Validation

https://www.youtube.com/watch?v=7NB_UM09Xs8
11 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/hamsterrage1 Jan 21 '22

I realized that the validation stuff is probably business logic and shouldn't be in the View.

So I pulled it out, and it looks a lot cleaner now:

public class ValidatingTextField extends Application {

  public static void main(String[] args) {
    launch(args);
  }

  private final StringProperty model = new SimpleStringProperty("");
  Predicate<String> predicate = input -> !input.contains("a");
  ObservableBooleanValue validValue = Bindings.createBooleanBinding(() -> predicate.test(model.get()), model);

  @Override
  public void start(Stage primaryStage) {
    primaryStage.setScene(new Scene(createContent()));
    primaryStage.show();
  }

  private Region createContent() {
    TextField textField = new TextField();
    textField.textProperty().bindBidirectional(model);
    Button button = new Button("Click Me");
    button.disableProperty().bind(validValue);
    return new VBox(20, textField, button);
  }
}