通过在约束中比较它们来验证两个表单字段

时间:2014-01-20 14:51:13

标签: forms validation scala playframework constraints

我目前正在与Scala约束作斗争。 我有一个case表来绑定表单和映射函数。

但我不知道如何通过比较它们来验证两个字段(第一个字段应该大于第二个字段)

目前我认为应该这样做:

模型/ JobRequest.scala

package models

case class AddJobRequest (
    exrange: Boolean, 
    exrangefrom: Int,
    exrangeto: Int
)

控制器/ Index.scala

package controllers

/* Code code code */

val jobAddForm = Form(
mapping(
  "exrange" -> boolean,
   tuple(
    "exrangefrom" -> number(min = 7, max=19),
    "exrangeto" -> number(min  = 8, max = 20)
   ).verifying("Start number is greater than the stop number!", /** MAGIC GOES HERE */)
  )(AddJobRequest.apply)(AddJobRequest.unapply))

如果exrangefrom大于exrangeto,是否有可能检查?或者这是一种使用临时约束来检查它的完全糟糕的方法吗?

1 个答案:

答案 0 :(得分:4)

您可以在verifying对象上使用mapping(...)!在您的情况下,可以通过以下方式比较exrangefromexrangeto

package controllers

/* Code code code */

val jobAddForm = Form(
  mapping(
    "exrange" -> boolean,
    "exrangefrom" -> number(min = 7, max=19),
    "exrangeto" -> number(min  = 8, max = 20)
  )(AddJobRequest.apply)(AddJobRequest.unapply)
  verifying(
    "Start number is greater than the stop number!",
    addJobRequest => addJobRequest.exrangefrom < addJobRequest.exrangeto
  )
)

希望这是你的期望;)