Intro to Spring Boot: Model Validation

Notes

Today we'll take the following three steps to enable validation in our program:

  • Annotate our models using the Java Validation API annotations
  • Check that our bound model objects are valid
  • Display error messages in the view

When adding validation to a model in a controller method, you need the Errors errors parameter to directly follow the parameter being validated. For example:

public String handlerMethod(Model model,
                @ModelAttribute @Valid someObject, Errors errors)

If you don't put the Errors parameter after the parameter with the @Valid attribute, you'll receive an HTTP error.

Code

We start this lesson with the code in the video-validation-start branch of the cheese-mvc repo: starting code

We end this lesson with the code in the video-validation-end branch of the cheese-mvc repo: ending code

References

  • Java Validation API Annotations
  • Hibernate Validator Annotations - NOTE: You must have the proper Hibernate package included as part of your project to use these. For us, they will be included as part of the spring-boot-starter-web dependency that is in our build.gradle file. This reference was not mentioned in the above video, but it will be discussed and used in the studio for this class.