Play框架中的自定义正则表达式验证-Scala
我是Play 2.3.x和Scala的新手,正在尝试实现表单输入验证.
I am new to Play 2.3.x and Scala and trying to implement a form input validation.
让我们说我有一个示例表格.
Let us say I have an example form.
val userForm = Form(
"firstName" -> nonEmptyText
)
我想对名字字段实施以下操作:
I want to implement something like this for the first name field:
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")
}
此外,我想将其与多个(链接的/逐步的)验证结合起来,以便能够显示:
Also, I want to combine this with multiple (chained/step wise) validations so as to be able to display :
- 如果未输入任何内容-请输入名字
- 如果您的名字是正确的,并且无法通过正则表达式验证-请输入一个有效的名字
我想开发一个通用的解决方案,以便可以将其用于所有领域.
I want to develop a generic solution so that I can use it for all the fields.
感谢任何帮助.
您可以使用verifying
.
val userForm = Form(
"firstName" -> nonEmptyText.verifying("Must contain letters and spaces only.", name => name.isEmpty || name.matches("[A-z\\s]+") )
)
那里有一些额外的逻辑(带有OR的name.isEmpty
),因为空字符串会触发两个验证错误.好像 一样,按照顺序将验证错误保持在触发状态,因此您也许可以避免使用序列中的第一个验证错误,但不要束手无策. .您可以根据需要将任意多个verifying
链接在一起.
There's a little extra logic there (name.isEmpty
with OR), because an empty string would trigger both validation errors. It seems like the validation errors are kept in order in which they're triggered, so you might be able to get away with using the first validation error in the sequence, but don't hold me to that. You can chain as many verifying
s together as you like.
通过使它们更加通用,我不能完全确定您的想法,但是您可以通过在Forms
对象中组合已有的验证器来制作自己的Mapping
验证器.
I'm not entirely sure what you have in mind by making these more generic, but you can make your own Mapping
validators by composing already existing ones in the Forms
object.
val nonEmptyAlphaText: Mapping[String] = nonEmptyText.verifying("Must contain letters and spaces only.", name => name.matches("[A-z\\s]+") )
然后您可以在Form
中使用它:
And then you can use it in the Form
:
val userForm = Form(
"firstName" -> nonEmptyAlphaText
)