Spring Validator – Spring Boot Validation Example

In the last article, we have seen how to create a simple spring boot rest example.

In this tutorial, we will take a look at the spring validator and how to create a custom validator for the bean validation.

To demonstrate the validators concept in spring boot, we will take a look at a few examples.

Why Validators required?

Let’s take an example of a User entity class.

The user entity has many properties (columns in the database) like id, user name, password, email, and contact number.

Therefore, how you will make sure that the client shouldn’t provide empty value for those properties.

For those types of validation, we can use annotations provided by Hibernate validators (JSR-380).

Hibernate validators in Spring Boot

Hibernate validators offer a few annotations that can be used to a bean property for validation purposes.

Spring boot by default add hibernate validator’s dependency and configure it on the classpath.

Therefore, we don’t have to write any code to add hibernate validator into our project.

So, Let’s change the above User class and add a constraint called @NotEmpty.

The above @NotEmpty will make sure that the client will provide some value for those bean properties.

If the client doesn’t provide a value, the client will get 500 internal error.

The above annotation doesn’t enable hibernate bean validation automatically.

How to enable Hibernate Bean Validation

There are two ways to enable bean validation.

  1. You can add @Valid (javax.validation) before request body.
  2. You can add @Validated above class Name

Enable Bean Validation using @Valid example (UserController.java)

Now if you trigger HTTP POST request, then MethodArgumentNotValidException will occur and HTTP 400 Bad Request result will be returned by Spring.

In the above scenario, spring won’t provide an error message along 400 code.

To provide a clear error message let’s override handleMethodArgumentNotValid in GlobalExceptionHandler.

Now let’s see the error message when we provide the empty email address

hibernate validator demo

Enable Bean Validation using @Validated at class Level (UserController.java)

Instead of adding @Valid before the request body, you can also provide @Validated at the class level.

In the case of validated failed, spring will throw ConstraintViolationException.

Let’s this exception in the GlobalExceptionHandle class.

Now let’s try to add a new User without providing his contact number. Spring will throw 500 internal error (BAD_REQUEST).

From the above logs, it is clear that when we don’t provide a required value (@NonEmpty) then we get 500 internal error with a clear exception ConstraintViolationException with the value “Please provide contact number”.

Let’s add a few more Hibernate Validators annotation to bean validation.

As you can see we have added a @Length annotation.

@Length annotation will validate that the user should provide a minimum 7 digit number and max 10 digits number.

Let’s hit the below request.

HTTP POST http://localhost:8080/api/user/add
{
“user_name”: “root”,
“password”: “linux”,
“email”: “[email protected]”,
“contact_number”: “898898”
}

Output:

It is clear that user will get 500 internal error if contact_number length is less than 7 digits or more than 10 digits.

In the above example, message = “Please provide contact number” is an error message.

You can also define an error message in the application.properties file.

application.properties file

To summarize, let’s look at the complete User.java file.

How to add a Custom Validator

Password validator hibernate
Password validator

If you look at the above post request, I have provided “lin ux” in the password field.

Although the above request was successful, you could observe that the password has space in between.

Let’s write a custom validator to check if the password has any space in between and throw an error if space is present.

Steps to create a custom validator

1. Create an annotation Password by providing its definition in Password.java

2. Create a validator PasswordValidator.java that implements ConstraintValidator.

3. Add @Password on password property of User class.

4. Now test the above changes, spring will throw an exception.

Conclusion

In this article, we discussed the importance of hibernate validators and how to create a custom validator.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.