如何使用 play framework case class 绑定确认密码字段?

How to have confirm password field using play framework case class bind?

我有两个模型:

case class User(uid: Option[Int], email: String, password: String, created_at: Timestamp, updated_at: Timestamp)

case class UserProfile(firstname: String, lastname: String, gender: Int, user_id: Int)

我在控制器中以表格形式绑定它:

val date = new Date()
  val currentTimestamp= new Timestamp(date.getTime());
  val registerForm = Form(
    tuple(
          "user" -> mapping(
            "uid" -> optional(number),
            "email" -> email,
            "password" -> nonEmptyText,
            "created_at" -> ignored(currentTimestamp),
          "updated_at" -> ignored(currentTimestamp)
        )  (User.apply)(User.unapply).verifying("Email already exists.", fields => fields match {
            case user => {
              val result = userDao.findByEmail(user.email)
              !result.isDefined
            }
          }),
        "profile" -> mapping(
          "firstname"->nonEmptyText,
          "lastname"->nonEmptyText,
          "gender" -> ignored(0),
          "user_id" -> ignored(0)
        )(UserProfile.apply)(UserProfile.unapply))
    )

我怎样才能在绑定的表单中有一个确认密码字段?我不能在模型案例 class 中使用它,因为我也将它用于我的 DAO Slick 操作,并且不值得再拥有一个具有类似特征的字段。

谢谢

我同意上面 Louis F 的观点,您应该将用户数据的接收与持久化分开。你可以有一个 DTO:

case class UserData(email: String, password: String, passwordCheck: String)

并使用与上面相同的方式使用 verifying 以确保 password == passwordCheck (因此只有匹配时表格才会绑定)。然后我会添加到 User 伴随对象:

object User {
  def apply(data: UserData): User = User(None, data.email, data.password, ...)
}

请注意,fields match { case user => ... } 只是将您的引用 "fields" 重命名为 "user",并且可以简化为 case 语句的正文。