0

我是 Play 2.3.x 和 Scala 的新手,并试图实现表单输入验证。

假设我有一个示例表格。

val userForm = Form(
   "firstName" -> nonEmptyText
)

我想为名字字段实现类似的东西:

 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”)
 }

另外,我想将此与多个(链接/逐步)验证结合起来,以便能够显示:

  1. 如果未输入任何内容 - 请输入名字
  2. 如果名字已输入且未通过正则表达式验证 - 请输入有效的名字

我想开发一个通用解决方案,以便我可以将它用于所有领域。

感谢任何帮助。

4

1 回答 1

6

您可以使用verifying.

val userForm = Form(
   "firstName" -> nonEmptyText.verifying("Must contain letters and spaces only.", name => name.isEmpty || name.matches("[A-z\\s]+") )
)

那里有一些额外的逻辑(name.isEmpty使用 OR),因为空字符串会触发两个验证错误。似乎验证错误按照触发它们的顺序保存的,因此您可能可以使用序列中的第一个验证错误而侥幸,但不要强迫我这样做。您可以将任意数量verifying的 s 链接在一起。

通过使这些更通用,我不完全确定您的想法,但是您可以通过在对象Mapping中组合已经存在的验证器来制作自己的验证器。Forms

val nonEmptyAlphaText: Mapping[String] = nonEmptyText.verifying("Must contain letters and spaces only.", name => name.matches("[A-z\\s]+") )

然后您可以在以下位置使用它Form

val userForm = Form(
   "firstName" -> nonEmptyAlphaText
)
于 2014-06-23T14:15:52.603 回答