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. 

About Author

Author Image
Prashank Jauhari

Prashank is quick learner and passionate about new technologies. He is currently working as Java Developer with knowledge of Spring and Hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..