Spring Boot – Validation using Hibernate Validator
Hibernate validators are very useful and they provide the following annotations that are very helpful for software development.
|@NotNull||Char Sequence, Collection, Map, or Array object can be validated with this and they should not be null but can be empty|
|@NotEmpty||Char Sequence, Collection, Map, or Array object can be validated with this and they should not be null and not empty|
|@NotBlank||Char Sequence, Collection, Map, or Array objects can be validated with this and they should not be null and not empty and not blank|
|@Min||Given Minimum value has to get satisfied|
|@Max||Given Maximum value has to get satisfied|
|@Size||Field size should be less than or greater than the specified field size|
|Email can be validated with this|
|@Pattern||Given RegEx Pattern has to be satisfied.|
Let us go with a sample project that includes Hibernate validator.
This is the maven project and hence the required dependencies need to be placed in pom.xml
Mandatory dependency for hibernate validator:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
Let us start with a bean class that can have the annotations
To collect all the errors, we need to have an “ExceptionHandler” and it is given below
Let us try to save the geekemployees by accepting the inputs like “geekEmployeeName”,”salary”,”geekEmailId” and “qualifications”. We need a rest controller file to achieve the same.
Our last step is to write the main class that starts the spring boot project. Via eclipse also it can be started as an ordinary java application or since it is a maven application, it can be started as
On running the application, in the console, we can see as follows
Let’s check the working part by using the postman client as we are using post mapping
By means of Hibernate validator, very easily front-end validations can be checked and that helps a lot in spring boot projects simply a dependency makes these kinds of validations to validate a page.
Please Login to comment...