i am creating a demo application using spring mvc 3.0.I have to apply the validation over the screen.I searches on the net and found that there is mainly 2 types of validation are used with the application :-
- Spring validations using validations Api
- Hibernate validation using hibernate validations
Hopefully somebody give me the suggestion which one is good one to implement in the application.
I used both – I like the Hibernate Validation more – pretty easy to implement and pretty standard. It is automatically enabled when you have an implementation on the classpath. Here is an example:
Where does the message Error String comes from? In WEB-INF you must have a file called messages.properties :
There is a standard @Email annotation, but an email such as : me@mycompany is considered valid, that is why I had to make my own @EmailValidator(changed a regex flag from * to + in the standard implementation).
There are some issues that I came across : the order of validation – which validation you want to happen first, this is done with Validation groups, but this are not possible with the @Valid annotation, for example :
That is why if you have your Controller in this form (in Spring MVC for example), then you have to simulate your logic in a way – I’ve done that also.
Another cool thing that you can do it to Validate two or more fields at at time (which I found pretty useful):
And the implementation :
The other FieldMatchImpl would be :
and you need two methods implemented:
Also:
Using org.apache.commons.beanutils.BeanUtils you can now validate the two fields.
Like this:
Other then that it has been a pleasure using the Hibernate Validation so far.