Play框架中的自定义正则表达式验证-Scala [英] Custom regex validation in Play Framework - Scala

查看:88
本文介绍了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 :

  1. 如果未输入任何内容-请输入名字
  2. 如果您的名字是正确的,并且无法通过正则表达式验证-请输入一个有效的名字

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

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 verifyings 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
)

这篇关于Play框架中的自定义正则表达式验证-Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆