I'm creating a Java desktop application and was wondering how I should deal with validation.
I receive an map with registration information (username, password, ...) in my controller. Now I want to validate the information from the map and display all errors that occur in the validation. So I was thinking of creating a custom class RegistrationValidation in a new package called validation. Then make this class return a List with errors. But I been wondering...
I've always learned that the validation should be done in the correct model class, is making a Validation class against the MVC principle?
Where should I call this validation class, from my controller or from my model?
How should I call the validation class? (make the methods static, make it a singleton, just make an instance of it in the controller/model or other?)
Are there any better solutions to extract validation?
Good question. If you have a Map you can easily create java bean from it. This java bean will be your model and it will have some kind of public validate
method which will return List of errors (Map of errors with key as property name and error message might work as well).
Surely, some aspects of validation can't be verified using only bean data(e.g. you'll need to call some other service to make sure that username wasn't already taken if that validation of sign up page). In this case you can pass extra parameters to validate
(services, etc).
Flow could be the next: getting data in controller, creating model (java bean), calling validate on it, returning list of errors(if any) to view, or forwarding to the next view. That's very typical workflow of MVC applications.
Oh, and don't make anything static, don't make it singletons. If you share validation across controllers just inject your validator in them. Check out spring framework. It might be useful for you.