custom Constraint in Play 2.0-scala?

2019-04-13 18:06发布

问题:

I want to write a custom Constraint to use it in my Form for validation. Mappings in Form have a verifying function: verifying (constraints: Constraint[T]*): Mapping[T].

I can obviously use the built in constraints, e.g. "name" -> text.verifying(nonEmpty).

Now I need my own constraint though. The Constraint case class looks like: case class Constraint [-T] (name: Option[String], args: Seq[Any], f: (T) ⇒ ValidationResult) extends Product with Serializable

But when I looked at ValidationResult, I just see an empty trait, see here - http://www.playframework.org/documentation/api/2.0.2/scala/index.html#play.api.data.validation.ValidationResult. So how can I define my own Constraint?

回答1:

Is your problem that you don't know how to create a function of type T => ValidationResult? If you click on the "known subclasses", it has two: Invalid (a class) and Valid (a singleton).

So for example:

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)