use*_*731 0 regex validation scala playframework playframework-2.3
我是Play 2.3.x和Scala的新手,并尝试实现表单输入验证.
我们假设我有一个示例表单.
val userForm = Form(
"firstName" -> nonEmptyText
)
Run Code Online (Sandbox Code Playgroud)
我想为名字字段实现类似的东西:
If a regex for first name (say firstName.regex = “regex for first name” ) is defined then {
Validate first name against specific regex
}else{
Validate against the global regex ( say global.regex = “global regex white list some regex valid for across the application”)
}
Run Code Online (Sandbox Code Playgroud)
此外,我想将其与多个(链式/逐步)验证相结合,以便能够显示:
我想开发一个通用解决方案,以便我可以将它用于所有领域.
感谢任何帮助.
你可以用verifying.
val userForm = Form(
"firstName" -> nonEmptyText.verifying("Must contain letters and spaces only.", name => name.isEmpty || name.matches("[A-z\\s]+") )
)
Run Code Online (Sandbox Code Playgroud)
那里有一些额外的逻辑(name.isEmpty使用OR),因为空字符串会触发两个验证错误.它看起来像验证错误都保存在其中他们为了引发的,所以你也许可以与序列中使用的第一个验证错误脱身,但不要抱着我说.您可以根据需要将尽可能多verifying的链接在一起.
通过使这些更通用,我不完全确定你的想法,但你可以Mapping通过组合Forms对象中已有的验证器来制作自己的验证器.
val nonEmptyAlphaText: Mapping[String] = nonEmptyText.verifying("Must contain letters and spaces only.", name => name.matches("[A-z\\s]+") )
Run Code Online (Sandbox Code Playgroud)
然后你可以在Form:
val userForm = Form(
"firstName" -> nonEmptyAlphaText
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1828 次 |
| 最近记录: |