Play 2.0标量中的自定义约束? [英] custom Constraint in Play 2.0-scala?

查看:81
本文介绍了Play 2.0标量中的自定义约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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].

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

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

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

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

但是当我查看ValidationResult时,我只是看到一个空的特征,请参见此处-

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?

推荐答案

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

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).

例如:

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)

这篇关于Play 2.0标量中的自定义约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆