gpt4 book ai didi

forms - 如何在 Play 中同时验证多个表单字段?

转载 作者:行者123 更新时间:2023-12-01 19:04:31 25 4
gpt4 key购买 nike

所以我有一个表单对象:

  object RegisterForm {
case class registerFormData(
name: String,
email: String,
repeatemail: String,
password: String,
repeatpassword: String,
timezone: Option[Int],
dob: Int,
accept: Boolean
)
val registerForm: Form[registerFormData] = Form(
mapping(
"name" -> nonEmptyText,
"email" -> nonEmptyText,
"repeatemail" -> nonEmptyText,
"password" -> nonEmptyText,
"repeatpassword" -> nonEmptyText,
"timezone" -> optional(number),
"dob" -> number,
"accept" -> checked("Please accept the terms and conditions.")
)(registerFormData.apply)(registerFormData.unapply)
)
}

我可以像在 Java 中的 Play 中一样同时验证多个字段吗?

例如,我可以验证密码和重复密码是否相等,检查以确保用户名未被占用,然后发回显示两个错误的表单?

最佳答案

像这样会更好:

case class User(
name: String,
email: String,
password: String,
timezone: Option[Int],
dob: Int,
accept: Boolean
)

val registerForm: Form[User] = Form(
mapping(
"name" -> nonEmptyText,
"email" -> tuple(
"main" -> nonEmptyText,
"confirm" -> nonEmptyText
).verifying(
"Emails don't match", email => email._1 == email._2
).transform[String](
email => email._1, // Transform to a single field
email => (email, email) // Reverse transform from a single field to multiple
),
"password" -> tuple(
"main" -> nonEmptyText,
"confirm" -> nonEmptyText
).verifying(
"Passwords don't match", password => password._1 == password._2
).transform[String](
password => password._1,
password => ("", "")
),
"timezone" -> optional(number),
"dob" -> number,
"accept" -> checked("Please accept the terms and conditions.")
)(User.apply)(User.unapply)
)

我个人还会从 Form 本身中删除 accept,并在选中“accept”复选框之前阻止用户使用提交按钮。使用这种方法,您可以减少引入案例类的垃圾量,并且根本不需要单独的案例类。 HTML 中的表单字段将如下所示:

Email: <input type="text" name="email.main">
Confirm Email: <input type="text" name="email.confirm">

您还可以使用验证表单中检查用户名或电子邮件地址是否已被使用,但我会将其保存到之后 表单已成功绑定(bind)。

如果您有像 User.findByEmail(string) 这样返回 Option[User] 的函数,您可以添加到 Form< 中的电子邮件字段:

.verifying("Email address is already in use", email => User.findByEmail(email).isEmpty)

关于forms - 如何在 Play 中同时验证多个表单字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26568321/

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