SpringBoot Form Validation with Binding Result
Posted By : Prashank Jauhari | 22-Sep-2017
Spring Boot Provide support of Form validation and it is helpful in removing redundant code for validating user inputs.
Step 1.
Create a domain with required validation Annotation on Class fields. Below code snippet provide a way to do that.

you need to place all the validation that needs to placed on fields. For example in the above code snippet name field cannot be empty , follow a particular pattern with minimum length 5 and maximum 5.
step2) Next we need to check is there any validation errors?

Whenever spring encounter any error related to validation hasError method of BindingResult will return true.
Note: It is mandatory to place @Valid annotation right before Domain Reference only then spring validate user input. You also need to Place a reference of binding result right after Domain that is being validated.
Step3 and Step4 contain code used to generate Response related to field Errors. You can write your own logic. Below code snippet provide modular and reusable code to generate ResponseEntity related to field errors.
Step3. Below code snippet provide a method to generate Map for the field with errors as key and their corresponding messages values.

Step4: Below code snippet provide a method to generate ResponseEntity related to field Error Response.

Notes : Code it step3 and step4 are reusable you can place them in your utility class and use them through out your application.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Prashank Jauhari
Prashank is quick learner and passionate about new technologies. He is currently working as Java Developer with knowledge of Spring and Hibernate.