Play 1.0 comes with a full featured validation framework base on http://oval.sourceforge.net/.
With the release of 2.0, my custom validators do not work anymore.
How does one create custom validator using Play Framework 2.0 ?
Play 1.0 comes with a full featured validation framework base on http://oval.sourceforge.net/.
With the release of 2.0, my custom validators do not work anymore.
How does one create custom validator using Play Framework 2.0 ?
In Play 2.0, the validation framework extends beyond the actual validation of the data as it reaches to:
The HTML Helpers are something new to Play 2.0. In 1.x, Play was already pretty good at enforcing a well defined validation framework. It was powerful and easy to use. Yet we still had to wire the HTML form and the validation framework together. This could be a little confusing to the beginner.
With Play 2.0, this is now done automatically.
But let's focus on the answer and provide some guidance: We will create an AllUpperCase validator, that generates an error either when:
The validator
The first thing you may notice is the import: Play 2.0 indeed complies with JSR 303 - Bean Validation Framework. In this context, the validator needs to implement ConstraintValidator. Which in our case translates into the annotation as class
AllUpperCase
(which we will introduce in a minute) and T as a genericObject
.The validator is straighforward:
We defined the method public boolean isValid(Object object) that returns a boolean, if true the validation passed. There is also an message id and a method that instanciates the validator.
The Annotation
The class below defines an annotation named
@AllUpperCase
which takes no parameters but enforces the validation defined previously. Providing details related to the annotation framework is outside the scope of this post.Note how the anotation glues to the other pieces of the puzzle.
@Constraint
, a JSR 303 annotation, links to the validator@play.data.Form.Display
, links the annotation to the play html helpers. Note that the name is important: we are defining a constraint named alluppercase. Play uses this information to call the methodpublic static play.data.validation.Constraints.Validator<Object> alluppercase()
on the Validator.Usage
We now have our custom validator and annotation
Describing the usage is outside the scope of this post, please find a working sample at this URL