javafx - TornadoFX:在ValidationContext中比较2个表单值

标签 javafx kotlin observable tornadofx

在tornadofx 中,我试图验证形式中输入的两个值是否相等。我遵循了this指南,一切正常。但是我遇到了我无法检查输入中的两个值是否相等的方法。

例如,假设我要创建一个简单的注册表单,在该表单中,我必须检查两个密码是否相等。我试过的是:

val validator = ValidationContext()

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

我调查了login example,希望可以在示例代码中找到帮助,但没有成功。

有没有办法在验证上下文中比较输入?如果可以,怎么办?

编辑:这确实有效,但是我认为这不是在验证上下文中检查输入的理想方法。有没有更好的办法?
if (password.get() != password2.get()) 
    error("Passwords do not equal") //Returns the error message 

最佳答案

您可以为每个字段创建验证器,以便将它们与另一个字段进行比较。然后,当某个字段更改时,您需要确保重新评估另一个字段的验证器。确保包括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()
                }
            }
        }
    }
}

关于javafx - TornadoFX:在ValidationContext中比较2个表单值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51944279/

相关文章:

c# - 单元测试Elastic Search Nest客户端-BulkAll

java - 调整 AnchorPane 中标签的大小

JavaFX 节点 - 如何让最终用户调整它们的大小?

android - LazyColumn 交换项目动画

android - kotlin 中内联函数的正确用法是什么?

oop - 如何在复杂的纸牌游戏中平衡多态/继承/TypeData架构与原型(prototype)/享元模式的技巧?

Javafx 线程加入交通灯 UI 上。如何同步线程?

Java:TableColumn 用于 2 个对象 Book 和 Author

angular - 将参数附加到 Observable 中的嵌套数组

javascript - 使用 ngrx/store 进行观察 - 竞争条件