| Start |
|---|
| JSR303 Annotation based validations in Springs examples Add any JSR 303 implementation to your classpath. Popular one used is Hibernate validator from Hibernate. Lets say the there is a rest api to create user in the system The input json sample would look like as below User.java We can define JSR 303 validations on User Class as below. We may also need to have a business validator like password and password2(confirm password) are same, for this we can add a custom validator as below. Write a custom annotation for annotating the data field. Write a Validator class for applying Validation logic. Adding this validation to User Class @Valid triggers validation in Spring. BindingResult is an object injected by spring which has list of errors after validation. JSR 303 annotation has message attributes on them which can be used for providing custom messages. |
| Spring JSR 303 Validation - Customize error messages Suppose we have a simple class with validation annotations A controller to check the UserDTO validity. And a test. Both name and age are invalid so in the BindingResult we have two validation errors. Each has array of codes. Codes for Min check And for NotEmpty check Let's add a custom.properties file to substitute default messages. If we add to the custom.properties file the line The new value is shown for the error. To resolve message validator looks through the codes starting from the beginning to find proper messages. Thus when we define If we define a message All annotations where we app min check to integer values use the newly defined message. The same logic could be applied if we need to localize the validation error messages. |
| @Valid usage to validate nested POJOs Suppose we have a POJO class User we need to validate. and a controller method to validate the user instance Let's extend the User with a nested POJO Address we also need to validate. Just add |
Read Article
https://develop.horje.com/learn/1434/reference