问题
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 :
- If nothing is entered - Please First name
- 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 verifying
s 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