Play 2.0-scala中的自定义约束?

Lux*_*ode 2 scala playframework playframework-2.0

我想编写一个自定义约束以在我的表单中使用它进行验证.Form中的映射具有验证功能:verifying (constraints: Constraint[T]*): Mapping[T].

我显然可以使用内置约束,例如"name" -> text.verifying(nonEmpty).

现在我需要自己的约束.Constraint案例类如下所示:case class Constraint [-T] (name: Option[String], args: Seq[Any], f: (T) ? ValidationResult) extends Product with Serializable

但是当我查看ValidationResult时,我只看到一个空洞的特征,请看这里 - http://www.playframework.org/documentation/api/2.0.2/scala/index.html#play.api.data.validation.ValidationResult.那么如何定义自己的约束呢?

Lui*_*hys 5

您的问题是您不知道如何创建类型的函数T => ValidationResult?如果单击"已知子类",它有两个:( Invalid一个类)和Valid(一个单例).

例如:

import play.api.data.validation._

val f = (_: Int) match {
  case 0 | 1 | 2 => Valid
  case _ => Invalid("Number over 2")
}

val c = Constraint("my constraint")(f)
Run Code Online (Sandbox Code Playgroud)