如何在Play框架2.x中集成URI参数和表单数据验证?

时间:2015-02-28 14:04:18

标签: validation scala playframework-2.0

例如,我有这样的路线:

PUT           /bob/:id           controllers.BobController.update(id: String)

BobController:

object BobController extends Controller {

    case class BobForm(status: Int)

    val bobForm = Form(
        mapping(
            "status" -> number(min = -11, max = 99)
        )(BobForm.apply)(BobForm.unapply)
    )

    def update(id: String) = Action.async { implicit request =>
        bobForm.bindFromRequest.fold(
            formWithErrors => BadRequest(views.html.bob(formWithErrors)),
            formBob =>
                if (id.trim.nonEmpty) {
                    val bob = Bob.update(id, formBob.status)
                    Redirect(routes.Application.showBob(bob.id)).flashing("success" -> "Bob saved!")
                } else {
                    BadRequest(views.html.bob(formBob, "ID is invalid"))
                }
        )
    }
}

你可以在这一行看到我必须手动验证id不是空白值:

if (id.trim.nonEmpty) {

我希望将id验证合并到表格映射中:

    case class BobForm(id: String, status: Int)

    val bobForm = Form(
        mapping(
            "id" -> nonEmptyText,
            "status" -> number(min = -11, max = 99)
        )(BobForm.apply)(BobForm.unapply)
    )

但如果我这样做,bobForm.bindFromRequest将失败,因为id参数不在请求的表单数据中。

那么有没有办法将像id这样的URI参数与Play的表格数据验证进行整合?

0 个答案:

没有答案