By Alvin Alexander. Last updated: April 11, 2018
If you ever need to include multiple Play Framework 2.6 validators for a template form field, the uri
field below shows the syntax that worked for me:
//see https://www.playframework.com/documentation/2.6.x/ScalaCustomValidations
//see https://www.playframework.com/documentation/2.6.x/ScalaForms
val form: Form[BlogPost] = Form (
mapping(
"title" -> nonEmptyText,
"blogContent" -> nonEmptyText,
"tags" -> nonEmptyText,
"description" -> nonEmptyText(maxLength = 160),
"uri" -> nonEmptyText
.verifying("error: must begin with a /", u => beginsWithSlash(u))
.verifying("error: invalid characters in uri", u => charsAreAllowedInUri(u))
)(BlogPost.apply)(BlogPost.unapply)
)
As shown, just call the verifying
method as many times as needed on the form field you want to validate with your custom functions.
The two custom validation methods I use in that example take a String
and return a Boolean
, as shown here:
// verify that a string begins with a slash
private def beginsWithSlash(s: String): Boolean = s.startsWith("/")
// make sure the characters in the string are legal in a uri
private def charsAreAllowedInUri(s: String): Boolean = {
val regex = "[0-9a-zA-Z-_]*"
s.matches(regex)
}
In summary, if you ever need to include multiple custom Play Framework validation functions for a form field, I hope this example is helpful.