gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:22:35 41 4
gpt4 key购买 nike

在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/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com