In the last few days I created some JPA entities which are used in a Web Application and filled by the user. So what’s next? Input validation. I don’t like JSF’s f:validator tag since it displays only one error message which might be useful if you put the error message next to the input filed. But if you display all error messages bundled on the top of the main content the messages are non-sense for the user.
The next possible solution would be the validator attribute of a JSF component. While this is appropriate for small forms it creates a lot of overhead in big forms (assume you have 10 input fields which follow different constraints). Also it leaves a “Do Repeat Yourself” taste in the delevoper’s mouth. Okay, so what’s the one and only solution.
As always I don’t think there is any but one that comes pretty close: JSR-303 aka Bean Validation. Emerged from Hibernate Validation this JSR aims to simplify bean validation. The JSR is currently in its final proposal stage hence the final release 1.0.0 should be near.
Instead of writing you own code you annotate your beans and tell the Validator what to look for. @NotNull e.g. tells the Validator that the value must not be null. The Rest of the validation is very very very easy:
final ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); final Validator addressValidator = factory.getValidator(); final Set> violations = addressValidator.validate(beanToValidate);
And with this set of violations you can display whatever error messages you want.
You can download it from the Sourceforge page of Hibernate Validator which also contains a very good “Getting started” guide which was (co-)written by Gunnar Morling. At his blog you can find two good introductions, too (Part1 and Part2). For further information just follow the blog of Gavin King et. al.
Or if you use Maven you can download it from JBoss’ Maven repository:
#1 by Peter on November 12, 2009 - 5:33 pm
JSR 303 integration for all JSF versions is available via MyFaces Extensions Validator (aka ExtVal)! A version for JSF 1.2 was deployed to the snapshot repository [1]. So this second milestone (of ExtVal v1.2.3) is ready to test.
[1] http://people.apache.org/repo/m2-snapshot-repository/org/apache/myfaces/extensions/validator/