custom Constraint in Play 2.0-scala?

拟墨画扇 提交于 2020-01-01 17:30:15

问题


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)


来源:https://stackoverflow.com/questions/11999202/custom-constraint-in-play-2-0-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!