首页 文章

自定义验证Play 2.0表单(scala)

提问于
浏览
4

我正在写一个小爱好的应用程序 . 现在,在我的应用程序中,我希望人们有一个userId(就像我的niklassaers在这里堆栈溢出),如果它已经被采用,我希望用户得到一个错误,以便他可以选择另一个 .

接下来是我的注册对象,它在“mapping(”:“对象表单中方法映射的缺少参数;”如果你想将它作为部分应用的函数处理,请使用`_'来表示错误

object Signup extends Controller {

  val userForm: Form[UserProfile] = Form(
    mapping(
      "userId" -> nonEmptyText,
      "passwordHash" -> nonEmptyText,
      "email" -> email
    ) verifying (
      "ThisIsATest", { case(userId, passwordHash, email) => true }
      // "UserID already taken", { DBService.exists(UserProfile.getClass().getName(), userId) }
      )(UserProfile.apply)(UserProfile.unapply))


  def index = Action {

    Ok(views.html.signup(userForm))
  }

  def register = Action { implicit request =>
    userForm.bindFromRequest.fold(
      errors => BadRequest(views.html.signup(errors)),
      user => Redirect(routes.Profile.index))
  }
}

正如您所看到的,我已经使用仅返回true的测试验证替换了我的查找服务,以使示例不那么复杂 . 为了完整性,这是我的UserDetail案例类:

case class UserProfile(
                   userId : String,
                   email: String,
                   passwordHash: String)

我是斯卡拉新手和玩新手,所以如果这是一个非常微不足道的问题,我很抱歉 . 但:

  • 自从收到此错误后,我做错了什么?

  • 这是添加我自己的验证的正确方法吗?

  • 后续问题:如果进展顺利,我会重定向,但是如何重定向到引用刚刚验证的表单的页面?

干杯

3 回答

  • 0

    最后解决了这个问题:验证不是映射后出现的东西,它是约束的东西 . 所以它应该是

    "userId" -> nonEmptyText.verifying( "UserID already taken", userId => DBService.exists(UserProfile.getClass().getName().replace("$", ""), userId) == false ),
    

    我希望这有助于其他有同样问题的人:-)

  • 4

    有点晚了,但无论如何......

    您可以对整个“表单支持对象”进行验证,而不是仅在您最终使用的单个字段上进行验证 . 这类似于您在问题描述中发布的第一个代码 . 问题是您的验证块需要在apply / unapply语句之后 .

    case class UserRegistration(username: String, password1: String, password2: String)
    
    val loginForm = Form(
      mapping(
        "username" -> email,
        "password1" -> text,
        "password2" -> text
      )
      (UserRegistration.apply)(UserRegistration.unapply)
      verifying ("Passwords must match", f => f.password1 == f.password2)
    )
    
  • 5

    甚至以后,但无论如何...... :)

    使用整个"form backing object"上的验证不允许您向表单中的各个字段添加错误 . 如果你想这样做,请参阅Play! framework 2.0: Validate field in forms using other fields

相关问题