Custom regex validation in Play Framework - Scala

▼魔方 西西 提交于 2019-12-10 12:19:13

问题


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. If nothing is entered - Please First name
  2. If first name is enetred and fails regex validation - Please enter a valid first name

I want to develop a generic solution so that I can use it for all the fields.

Appreciate any help.


回答1:


You can use verifying.

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

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.

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]+") )

And then you can use it in the Form:

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


来源:https://stackoverflow.com/questions/24367718/custom-regex-validation-in-play-framework-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!