I am writing a form controller to edit a user and was wondering where to best place the data binding and validation. The Spring documentation states that validation should not be placed in the web tier:
5. Validation, Data Binding, and Type Conversion
There are pros and cons for considering validation as business logic, and Spring offers a design for validation (and data binding) that does not exclude either one of them. Specifically validation should not be tied to the web tier, should be easy to localize and it should be possible to plug in any validator available. Considering the above, Spring has come up with a Validator interface that is both basic ands (sic.) eminently usable in every layer of an application.
This certainly makes sense if I want to check that an updated username is unique and does not clash with a username already stored in the database. I don't want to hit the database in my web tier but in a service that calls a DAO.
My problem is that validation and error reporting seems to go well with Spring's data binding which I imagine should be in the web tier controller? Spring's data binding and validation integration appears to mean that validation will be automatically performed by Spring in the controller - long before I pass the data onto the service.
If I do all the validation in the service how should I report errors? Throw an exception that I catch in the controller and manually convert into a binding errors object?
Is it okay to do basic validation in the controller (e.g. password == password verification) and more advanced validation in the service?
Any references to authoritative works would be much appreciated - I can think of lots of ways of doing this - I just wondered which was is best?
I like you because you always keep good, crunchy cereal in your pantry. This tiny ad agrees:
Sauce Labs - World's Largest Continuous Testing Cloud for Websites and Mobile Apps