Skip to main content

REST tutorial : validations


Our API is all good but it currently accepts empty Todos. Let's fix that with validations.

You can find the complete source code here Todoapp

Hibernate Validator

Hibernate Validator allows to express and validate application constraints.
Implements JSR 380 bean validation api.
Hibernate validator is entirely separate from the persistence aspects of Hibernate.

Hibernate Validator 6.0 is the Reference Implementation of the Bean Validation 2.0 specification.


  • Update gradle
  • compile('javax.validation:validation-api:2.0.1.Final')
  • Update controller method to add @Valid check
  • Update TodoDto with validators
  • Catch validation exception in global exception handler (MethodArgumentNotValidException)

Useful annotations

@Length(min=, max=) - check if the string length match the range
@Max(value=) - check if the value is less than or equals to max
@Min(value=) - check if the value is less than or equals to min
@NotNull(value=) - check if the value is not null
@NotEmpty - check if the string is not null nor empty
@Past - check if the date is in the past
@Future - check if the date is in the future
@Email - check whether the string is valid email address
@Size(min=, max=) - check if the element size is between min and max (included)
@AssertTrue, @AssertFalse - true, false
@Positive -  check if the value is positive
@Negative - check if the value is negative

With that, we have completed section 2 of our REST API.