I have an User object that has many attributes. In my edit profile screen I’m displaying a subset of those attributes. In the corresponding controller action how can I validate only those fields that are being edited and not all the fields in the User object?
I have annotated the fields in the User object with the MaxSize, Email, URL, etc. constraints and don’t want to repeat them again by validating each field manually.
Any pointers would be greatly appreciated. Thanks!
the simplest way is to pass the full object to the receiving method and just validate all of it. As you are only editing a subset of fields, they will be the only ones changing and the ones that will trigger an error if the validation fails. This is, of course, assuming that you never store invalid objects in the database!
If not, you can also create a support bean that doesn’t extend from Model, with validation tags, and pass that to the form and controller. Something like:
In both cases it would be something like this, replacing the full object User by a temporary object if needed (double check the code, I don’t have Play environment here and I may do some typos/small mistakes)
And then in the controller:
Add a POST rule to ‘save’ int he routes file, and you are ready to go.
The framework has a sample project (validation I think its the name) which contains 7 different ways of doing validation. The last one uses JQuery to reuse the validation tags of your class and run the same validation in the client before committing. Give them a look, they may help you a lot 🙂