gpt4 book ai didi

forms - 如何为 play2 的表单定义 StopOnFirstFail dsl?

转载 作者:行者123 更新时间:2023-12-04 05:53:48 25 4
gpt4 key购买 nike

在这个问题中:If a form field has multi validators, how to let play verify them one by one, not all? , Julien 给了我一个名为 stopOnFirstFail 的方法解决我的问题:

def stopOnFirstFail[T](constraints: Constraint[T]*) = Constraint { field: T =>
constraints.toList dropWhile (_(field) == Valid) match {
case Nil => Valid
case constraint :: _ => constraint(field)
}
}

它的用法是:

val loginForm = Form(
"name" -> (text verifying stopOnFirstFail( nonEmpty, minLength(4) ))
)

但我希望定义一个可以用作的 dsl:

val loginForm = Form(
"name" -> (text verifying ( nonEmpty or minLength(4) ))
)

我试图为 play.api.data.validation.Constraint 定义一个隐式方法:

import play.api.data.validation._

implicit def _Constraint[T](cons: Constraint[T]) = new {

def or[T](other: Constraint[T]) = Constraint { field: T =>
cons(field) match { // (!)
case Valid => other(field)
case invalid => invlaid
}
}
}

但无法编译,错误在 (!) 行,消息为:
type mismatch; 
found: field.type (with underlying type T) required: T
Note: implicit method _Constraint is not applicable here
because it comes after the application point and it lacks an explicit result type

如何解决?

最佳答案

or方法不接受类型参数:

implicit def toLazyOr[T](cons: Constraint[T]) = new {
def or(other: Constraint[T]) = Constraint { field: T =>
cons(field) match {
case Valid => other(field)
case Invalid => Invalid
}
}
}

关于forms - 如何为 play2 的表单定义 StopOnFirstFail dsl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9759660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com