0

I have two fields: username and password. I want a button to remain disabled if these fields are blank or their length is less and n characters.

I tried using button disableProperty() in my controller but I want to do the validation in the FXML file. I don't know if it's possible or not.

My current validation:

    @FXML
    private TextField usernameField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private Button signinButton;

    // Runs on initializing
    @Override
    protected void configure() {
        signinButton.disableProperty().bind(usernameField.textProperty().isEmpty()
                .or(usernameField.textProperty().length().lessThan(5))
                .or(passwordField.textProperty().isEmpty())
                .or(passwordField.textProperty().length().lessThan(4)));
    }

FXML file:

<TextField fx:id="usernameField" prefHeight="34.0" prefWidth="220.0" promptText="Username"/>
<PasswordField fx:id="passwordField" prefHeight="34.0" prefWidth="220.0" promptText="Password"/>
<Button fx:id="signinButton" mnemonicParsing="false" onAction="#onSignin" prefWidth="220.0" text="Sign in"/>

Thanks in advance!

5
  • 5
    Why? That's what controllers are made for.
    – mipa
    Commented Jan 7, 2023 at 21:43
  • 1
    I though it's better to separate the view validations and logic code. Commented Jan 7, 2023 at 21:46
  • Then don't put logic code in your FXML controller.
    – DaveB
    Commented Jan 7, 2023 at 23:13
  • This is “view logic”, which belongs in the controller. The Eden coding tutorial in MVC nicely distinguishes between “view logic” (controller) and “business logic” (model).
    – James_D
    Commented Jan 8, 2023 at 15:40
  • @James_D unfortunately the eden coding tutorial in MVC is broken. Most of the content is missing. The part obout view vs business is still there without the examples anymore. Luckily the content can still be found in the wayback machine.
    – jewelsea
    Commented Jan 8, 2023 at 16:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.