首页 > 解决方案 > TornadoFX: Compare 2 form values in ValidationContext

问题描述

In tornadofx, I am trying to validate if two values of inputs in a form equal. I followed this guide and everything works as expected. But I encountered that I have no way how to check if the two values in inputs equal.

For example, let's say I want to create the simple registration form where I have to check if the 2 passwords equal. What I tried was:

val validator = ValidationContext()

validator.addValidator(this, this.textProperty()) {
    if(!password!!.isEqualTo(it).get()) //password1 != password2 -> does not work
        error("Passwords do not equal")
}

I looked into the login example hoping I would find help in the example code but without success.

Is there a way to compare the inputs in the validation context? If so how?

EDIT: This does work but I don't think it is the desired way to check the inputs in the validation context. Is there a better way?

if (password.get() != password2.get()) 
    error("Passwords do not equal") //Returns the error message 

标签: javafxkotlinobservabletornadofx

解决方案


您可以为每个字段创建验证器,以便它们与另一个字段进行比较。然后,您需要确保在更改字段时重新评估其他字段的验证器。当您在输入字段中进行更改时,请确保包括focusFirstError = false以避免焦点转移。

class DualValidationForm : View() {
    private val vm = object : ViewModel() {
        val text1Property = bind { SimpleStringProperty() }
        val text2Property = bind { SimpleStringProperty() }
    }

    override val root = form {
        fieldset("Make sure both fields have the same value") {
            field("Text 1") {
                textfield(vm.text1Property) {
                    validator {
                        if (it == vm.text2Property.value) null else ValidationMessage("Not the same!", ValidationSeverity.Error)
                    }
                    vm.text1Property.onChange {
                        vm.validate(focusFirstError = false, fields = vm.text2Property)
                    }
                }
            }
            field("Text 2") {
                textfield(vm.text2Property) {
                    validator {
                        if (it == vm.text1Property.value) null else ValidationMessage("Not the same!", ValidationSeverity.Error)
                    }
                    vm.text2Property.onChange {
                        vm.validate(focusFirstError = false, fields = vm.text1Property)
                    }
                }
            }
            button("You can click me when both fields have the same value") {
                enableWhen(vm.valid)
                action {
                    information("Yay!", "You made it!").show()
                }
            }
        }
    }
}

推荐阅读