JavaFX Tutorials

Tuesday, September 13, 2016

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is used to apply the email validation rules to a TextField.  This is hooked in to the JavaFX program using a compound Binding expression.


The previous post shows the Scene Builder and a video demo.  The previous post allowed invalid email as it's purpose was to demonstrate equality between the two TextFields.  That input is no longer supported.  Rather, the email TextFields must contain a valid email, something of the form "user@host.com".

Here is a demo of the re-worked functionality.


First, I add the Commons Validator to my Gradle project.

    compile group: 'commons-validator', name: 'commons-validator', version: '1.4.0'

Next, in the initialize() method, I create a Commons Validator object.

        EmailValidator emailValidator = EmailValidator.getInstance();

I then create a StringBinding.  The StringBinding will return the input if the input adheres to the Commons Validator rules.  If the rules are not followed, the empty string is returned. For example, entering "javafx@example.com" would return "javafx@example.com" while simply "javafx" would return "".

        StringBinding validEmailExpr = Bindings.createStringBinding(
                () -> emailValidator.isValid(txtEmail.getText())?txtEmail.getText():"",
                txtEmail.textProperty()
        );

The Callback argument does the rule check.  The txtEmail.textProperty() argument is the "trigger" that will make this check called for each and every change of txtEmail.

This allows me to leverage the isEqualTo() method on the txtEmail TextField.  If the input matches the returned validation value, that clause will pass.  Otherwise, that clause will not be met.  The special case of an empty value in the TextField matching an empty value returned from the StringBinding is handled with the isEmpty() clause of the compound expression.

Finally, here is the compound Binding expression.

        btnSave.disableProperty().bind(
            txtEmail.textProperty().isEqualTo(txtConfirmEmail.textProperty()).not()
                .or(
                    txtEmail.textProperty().isEqualTo( validEmailExpr ).not()
                )
                .or(
                    txtEmail.textProperty().isEmpty()
                )
        );

No comments:

Post a Comment