gpt4 book ai didi

scala - 如何在Play 2中指定复杂的表单验证?

转载 作者:行者123 更新时间:2023-12-04 03:16:30 25 4
gpt4 key购买 nike

我了解如何在Play 2中添加简单的表单验证,例如nonEmptyText,但是我将如何实现更复杂的验证,例如“必须定义至少一个字段”?目前,如果我使用所有None初始化了模型对象,则会在其模型对象中引发异常,但这会产生令人讨厌的错误消息。我希望在表单页面上收到友好的错误消息。

最佳答案

您可以将mappings/tuples嵌套在表单定义中,并在映射,子映射,元组和子元组上添加verifying规则。
然后,在模板中,您可以使用form.errors("fieldname")检索特定字段或一组字段的错误。

例如 :

val signinForm: Form[Account] = Form(
mapping(
"name" -> text(minLength=6, maxLength=50),
"email" -> email,
"password" -> tuple(
"main" -> text(minLength=8, maxLength=16),
"confirm" -> text
).verifying(
// Add an additional constraint: both passwords must match
"Passwords don't match", password => password._1 == password._2
)
)(Account.apply)(Account.unapply)
)

如果您有两个不同的密码,则可以使用 form.errors("password")检索模板中的错误。

在此示例中,您将必须编写自己的 Account.applyAccount.unapply来处理 (String, String, (String, String))

关于scala - 如何在Play 2中指定复杂的表单验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10342151/

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