【问题标题】:custom Constraint in Play 2.0-scala?Play 2.0-scala中的自定义约束?
【发布时间】:2012-08-17 02:58:53
【问题描述】:

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

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

现在我需要自己的约束。约束案例类看起来像: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。那么如何定义自己的约束呢?

【问题讨论】:

    标签: scala playframework playframework-2.0


    【解决方案1】:

    您的问题是您不知道如何创建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)
    

    【讨论】:

    • 宾果游戏..这正是我的问题
    猜你喜欢
    • 2014-12-06
    • 2012-06-09
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2015-12-29
    • 2016-12-05
    • 2016-11-23
    • 1970-01-01
    相关资源
    最近更新 更多