spring boot validation

spring boot validation

Spring boot validation and Custom Validations

Spring boot validation is probably one of the cool features spring has to provide. Not only spring provided validations but also, it allows custom validation as well.

Custom Spring boot validator will allow you to act like the native validator in your application. Not only that, once you create custom spring validator, you can reuse it.

What is spring validator

Spring validator allows validating the data of the request. The validator will handle basic logic of handling validation than re-inventing the wheel.

Good example of Spring boot validation is using @Min and @Max validators on your numeric data. By adding those annotations to the class from javax.validation.constraints.Min, it checks if the value passed is with in the right range.

Spring boot validation also allows to write your own custom validator as well. Though spring validators cover lots of area, still one might get his/her own validator scenario and write that.

Spring boot validator example

Spring validator tutorial in action
Let’s have an example of spring boot validation in action.

I will be using Authentication request as an example.

In most websites, authentication is required. For that, the user will pass the username/email and password to verify his/her account. Hence we have to validate the data coming from the request for correct ness.

  • Check both email and password are provided
  • Check the email is with the right format
  • And finally they are not empty

Now the above requirement needs its own logic to be correctly handled right? But, Spring boot validation has already provided those validators through simple annotation and all we have to do will be to use those annotations.


package com.solutionladder.ethearts.model.request;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
/**
 * @author Kaleb Woldearegay 
 */
public class AuthenticationRequest {

    @Email(message="Invalid Email provided")
    private String email;

    @NotEmpty(message="Password cannot be null")
    private String password;

    ..setters/..getters..
}

As you can see above, by using the right annotations, all the validations of the request data is handled properly. Validating authentication request can be as simple as this one. On the next part, I will show you how you will be using the validation before handling you main logic.

On the above example, authentication controller is expecting email and password to be in order. Spring boot validation will handle those requirements as needed.

How to use spring boot validator in controller

How do I access spring boot validation
How to get spring boot validation response

Spring boot validation will provide the report of what has been failed and what has been passed. You can get the report of the validation and act upon it. Also you need the validation result to report it back to the front end to access better result. So how do we get validator result from spring?

Lets follow the authentication validation result. We will have the controller that will be accessing the authentication object and we will handle the validation as follows:


...in the controller...
 @PostMapping(path = { "/login", "/login/" }, consumes = "application/json", produces = "application/json")
    public ResponseEntity login(@Valid @RequestBody AuthenticationRequest loginRequest, BindingResult bindingResult) {
        Member member = this.memberService.findByEmailAndPassword(loginRequest.getEmail(), loginRequest.getPassword());
        if (bindingResult.hasErrors()) {
            //throw some exception with 403 or 400 error
        }

        //happy :) I have reached here and no problem so far
    }

In order to use validation @valid has to be provided along with the RequestBody.

The above snippet shows how to access the result of the spring validation. The BindingResult contains the result you are looking for. By checking the hasErrors() the logic decided what to do with the response.

The BindingResult is injected by Spring boot and can be accessed directly.

More to come on custom spring boot validation

Any problem implementing spring boot? Ask me on the comment area and will get back to you.

Good luck.

Removing a decorator from Zend Form

Leave a Reply

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

*
*