如何在Play中一次验证多个表单字段?

时间:2014-10-25 23:32:52

标签: forms validation playframework playframework-2.3

所以我有一个表单对象:

  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)
  )
}

我可以像在Play中使用Java一样验证多个字段吗?

例如,我可以验证检查密码和repeatpassword是否相同,检查以确保没有使用用户名,然后发回表单显示两个错误?

1 个答案:

答案 0 :(得分:5)

这样的事情会更好:

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)
)

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

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

如果用户名或电子邮件地址已被使用,您也可以使用verifyingForm内查看,但我会在<{em> {{ 1}}已成功绑定。

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

Form