javafx - 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
解决方案
您可以为每个字段创建验证器,以便它们与另一个字段进行比较。然后,您需要确保在更改字段时重新评估其他字段的验证器。当您在输入字段中进行更改时,请确保包括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()
}
}
}
}
}
推荐阅读
- python - 如何不断重复输入语句?
- python - 检查字符串列表中是否包含特定的字母或字符(python)
- javascript - 尝试在 Javascript 中执行 Luhns 算法,但我的编程一直无限循环
- flutter - 为什么动画容器不适用于 Flutter 中的形状?
- c# - 如何模拟 DynamodbContext BatchWrite 以在网络中进行单元测试
- python - fbs python安装程序的KERNELBASE.dll错误
- python - Pandas .loc 在大型索引数据集中超慢
- c++ - 第二个算法如何变得比第一个更有效,子数组的右侧如何在第二个算法中移动?
- oauth-2.0 - JWT 访问令牌是否应该包含 PII?
- sql-server - 使用 TypeORM 处理对 Azure SQL 数据库的大量插入的最佳方法