如果一个表单字段具有多个验证器,那么如何让它们逐个而不是全部对它们进行验证? [英] If a form field has multi validators, how to let play verify them one by one, not all?
问题描述
我有一个登录表单,有一个name
输入有很多验证器:
I have a login form in view, there is a name
input has many validators:
object Users extends Controller {
val loginForm = Form(tuple(
"name" -> (
nonEmptyText // (1)
verifying ("Its length should >= 4", name=>{ println("#222");name.length>=4 }) // (2)
verifying ("It should have numbers and letters", name=>{println("#333"); ...}) // (3)
)
}
然后我什么也没输入,按提交,发现控制台打印了
Then I don't input anything, press submit, and I found the console prints:
#222
#333
这意味着所有验证者都已执行,并且它们之间具有关系:
That means all validators performed, and they have relationship:
(1) & (2) & (3)
但是我希望他们:
(1) && (2) && (3)
这意味着,如果名称为空,则后面的两个验证器将被忽略.
That means, if the name is empty, the later two validators will be ignored.
在play2中可以吗?
Is it possible in play2?
推荐答案
默认行为是对字段定义所有约束. 但是,您可以定义自己的验证约束,以在第一次失败时停止应用约束:
The default behavior is to apply all the constraints defined on a field. However, you can define your own validation constraint that stops applying constraints on the first fail:
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)
))
)
scala> loginForm.bind(Map("name"->"")).errors
res2: Seq[play.api.data.FormError] = List(FormError(name,error.required,WrappedArray()))
scala> loginForm.bind(Map("name"->"foo")).errors
res3: Seq[play.api.data.FormError] = List(FormError(name,error.minLength,WrappedArray(4)))
scala> loginForm.bind(Map("name"->"foobar")).errors
res4: Seq[play.api.data.FormError] = List()
(请注意,我在stopOnFirstFail
的实现中应用了失败约束的两倍,因此该约束没有副作用)
(Note that my implementation of stopOnFirstFail
applies two times the failing constraint, so this one should not have side effects)
这篇关于如果一个表单字段具有多个验证器,那么如何让它们逐个而不是全部对它们进行验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!