gpt4 book ai didi

validation - Play 验证 - 具有特定字段错误的自定义表单字段验证

转载 作者:行者123 更新时间:2023-12-02 21:30:13 25 4
gpt4 key购买 nike

case class Address(
address1: String,
city: String,
state: String,
postal: String,
country: String
)

Form(
mapping = mapping(
"address1" -> nonEmptyText,
"city" -> nonEmptyText,
"state" -> nonEmptyText,
"postal" -> nonEmptyText,
"country" -> nonEmptyText
)(Address.apply)(Address.unapply).verifying("Invalid Postal Code!", validatePostal _)
)

def validatePostal(address: Address): Boolean = {
address.country match {
case "US" | "CA" =>
val regex: Regex = ("^(\\d{5}-\\d{4}|\\d{5}|\\d{9})$|^([a-zA-Z]\\d[a-zA-Z]( )?\\d[a-zA-Z]\\d)$").r
regex.pattern.matcher(address.postal).matches()
case _ => false
}
}

上述邮政编码表单验证工作正常,对于无效的美国或加拿大邮政编码,表单上显示全局错误。

我希望将错误显示为字段旁边的字段错误,而不是显示为全局错误,在我的情况下,全局错误显示在表单顶部。

有没有办法使用内置的表单约束或验证方法来实现此目的,而不是 FormError 的?

最佳答案

您可以将约束添加到该字段。然后更新 validatePostal 以接受两个值的元组。

Form(
mapping = mapping(
"address1" -> nonEmptyText,
"city" -> nonEmptyText,
"state" -> nonEmptyText,
"postal" -> tuple(
"code" -> nonEmptyText,
"country" -> nonEmptyText
).verifying("Invalid Postal Code!", validatePostal _),
)((address1, city, state, postal) => Address(address1, city, state, postal._1, postal._2))((address: Address) => Some((address.address1, address.city, address.state, (address.postal, address.country))))
)

模板:

@inputText(
addressForm("postal.code"),
'_label -> "Postal code",
'_help -> "Please enter a valid postal code.",
'_error -> addressForm.error("postal")
)

关于validation - Play 验证 - 具有特定字段错误的自定义表单字段验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22491242/

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