2012-08-17 78 views
2

我想寫一個自定義約束在我的表單中用於驗證。 Form中的映射具有驗證功能:verifying (constraints: Constraint[T]*): Mapping[T]Play 2.0-scala中的自定義約束?

我明顯可以使用內置的約束,例如, "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。那麼我怎樣才能定義我自己的約束?

回答

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) 
+0

bingo..that正是我的問題 – LuxuryMode 2012-08-17 03:59:16