Introduction

This article is focused on providing clear, simple, actionable guidance for providing Java Bean Validation security functionality in your applications.

Bean validation (JSR303 aka Bean Validation 1.0 /JSR349 aka Bean Validation 1.1) is one of the most common ways to perform input validation in Java. It is an application layer agnostic validation spec which provides the developer with the means to define a set of validation constraints on a domain model and then perform validation of those constraints through out the various application tiers.

One advantage of this approach is that the validation constraints and the corresponding validators are only written once, thus reducing duplication of effort and ensuring uniformity:

Typical Validation

Typical

Bean Validation

JSR

Setup

The examples in this guide use Hibernate Validator (the reference implementation for Bean Validation 1.1).

Add Hibernate Validator to your pom.xml:

  1. <dependency>
  2. <groupId>org.hibernate</groupId>
  3. <artifactId>hibernate-validator</artifactId>
  4. <version>5.2.4.Final</version>
  5. </dependency>

Enable bean validation support in Spring’s context.xml:

  1. <beans:beans ...
  2. ...
  3. <mvc:annotation-driven />
  4. ...
  5. </beans:beans>

For more info, please see the setup guide

Basics

In order to get started using Bean Validation, you must add validation constraints (@Pattern, @Digits, @Min, @Max, @Size, @Past, @Future, @CreditCardNumber, @Email, @URL, etc.) to your model and then utilize the @Valid annotation when passing your model around in various application layers.

Constraints can be applied in several places:

  • Fields
  • Properties
  • Classes

For Bean Validation 1.1 also on:

  • Parameters
  • Return values
  • Constructors

For the sake of simplicity all the examples below feature field constraints and all validation is triggered by the controller. Refer to the Bean Validation documentation for a full list of examples.

When it comes to error handling, the Hibernate Validator returns a BindingResult object which contains a List<ObjectError>. The examples below feature simplistic error handling, while a production ready application would have a more elaborate design that takes care of logging and error page redirection.

Pre-defined Constraints

@Pattern

Annotation:

@Pattern(regex=,flag=)

Data Type:

CharSequence

Use:

Checks if the annotated string matches the regular expression regex considering the given flag match. Please visit OWASP Validation Regex Repository for other useful regex’s.

Reference:

Documentation

Model:

  1. import org.hibernate.validator.constraints.Pattern;
  2. public class Article {
  3. //Constraint: Alpha Numeric article titles only using a regular expression
  4. @Pattern(regexp = "[a-zA-Z0-9 ]")
  5. private String articleTitle;
  6. public String getArticleTitle() {
  7. return articleTitle;
  8. }
  9. public void setArticleTitle(String articleTitle) {
  10. this.articleTitle = articleTitle;
  11. }
  12. ...
  13. }

Controller:

  1. import javax.validation.Valid;
  2. import com.company.app.model.Article;
  3. @Controller
  4. public class ArticleController {
  5. ...
  6. @RequestMapping(value = "/postArticle", method = RequestMethod.POST)
  7. public @ResponseBody String postArticle(@Valid Article article, BindingResult result,
  8. HttpServletResponse response) {
  9. if (result.hasErrors()) {
  10. String errorMessage = "";
  11. response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  12. List<ObjectError> errors = result.getAllErrors();
  13. for(ObjectError e : errors) {
  14. errorMessage += "ERROR: " + e.getDefaultMessage();
  15. }
  16. return errorMessage;
  17. } else {
  18. return "Validation Successful";
  19. }
  20. }
  21. }

@Digits

Annotation:

@Digits(integer=,fraction=)

Data Type:

BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types; Additionally supported by HV: any sub-type of Number

Use:

Checks whether the annotated value is a number having up to integer digits and fraction fractional digits

Reference:

Documentation

Model:

  1. import org.hibernate.validator.constraints.Digits;
  2. public class Customer {
  3. //Constraint: Age can only be 3 digits long or less
  4. @Digits(integer = 3, fraction = 0)
  5. private int age;
  6. public String getAge() {
  7. return age;
  8. }
  9. public void setAge(String age) {
  10. this.age = age;
  11. }
  12. ...
  13. }

Controller:

  1. import javax.validation.Valid;
  2. import com.company.app.model.Customer;
  3. @Controller
  4. public class CustomerController {
  5. ...
  6. @RequestMapping(value = "/registerCustomer", method = RequestMethod.POST)
  7. public @ResponseBody String registerCustomer(@Valid Customer customer, BindingResult result,
  8. HttpServletResponse response) {
  9. if (result.hasErrors()) {
  10. String errorMessage = "";
  11. response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  12. List<ObjectError> errors = result.getAllErrors();
  13. for( ObjectError e : errors) {
  14. errorMessage += "ERROR: " + e.getDefaultMessage();
  15. }
  16. return errorMessage;
  17. } else {
  18. return "Validation Successful";
  19. }
  20. }
  21. }

@Size

Annotation:

@Size(min=, max=)

Data Type:

CharSequence, Collection, Map and Arrays

Use:

Checks if the annotated element’s size is between min and max (inclusive)

Reference:

Documentation

Model:

  1. import org.hibernate.validator.constraints.Size;
  2. public class Message {
  3. //Constraint: Message must be at least 10 characters long, but less than 500
  4. @Size(min = 10, max = 500)
  5. private String message;
  6. public String getMessage() {
  7. return message;
  8. }
  9. public void setMessage(String message) {
  10. this.message = message;
  11. }
  12. ...
  13. }

Controller:

  1. import javax.validation.Valid;
  2. import com.company.app.model.Message;
  3. @Controller
  4. public class MessageController {
  5. ...
  6. @RequestMapping(value="/sendMessage", method=RequestMethod.POST)
  7. public @ResponseBody String sendMessage(@Valid Message message, BindingResult result,
  8. HttpServletResponse response){
  9. if(result.hasErrors()){
  10. String errorMessage = "";
  11. response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  12. List<ObjectError> errors = result.getAllErrors();
  13. for( ObjectError e : errors){
  14. errorMessage+= "ERROR: " + e.getDefaultMessage();
  15. }
  16. return errorMessage;
  17. }
  18. else{
  19. return "Validation Successful";
  20. }
  21. }
  22. }

@Past / @Future

Annotation:

@Past, @Future

Data Type:

java.util.Date, java.util.Calendar, java.time.chrono.ChronoZonedDateTime, java.time.Instant, java.time.OffsetDateTime

Use:

Checks whether the annotated date is in the past / future

Reference:

Documentation

Model:

  1. import org.hibernate.validator.constraints.Past;
  2. import org.hibernate.validator.constraints.Future;
  3. public class DoctorVisit {
  4. //Constraint: Birthdate must be in the past
  5. @Past
  6. private Date birthDate;
  7. public Date getBirthDate() {
  8. return birthDate;
  9. }
  10. public void setBirthDate(Date birthDate) {
  11. this.birthDate = birthDate;
  12. }
  13. //Constraint: Schedule visit date must be in the future
  14. @Future
  15. private String scheduledVisitDate;
  16. public String getScheduledVisitDate() {
  17. return scheduledVisitDate;
  18. }
  19. public void setScheduledVisitDate(String scheduledVisitDate) {
  20. this.scheduledVisitDate = scheduledVisitDate;
  21. }
  22. ...
  23. }

Controller:

  1. import javax.validation.Valid;
  2. import com.company.app.model.DoctorVisit;
  3. @Controller
  4. public class DoctorVisitController {
  5. ...
  6. @RequestMapping(value="/scheduleVisit", method=RequestMethod.POST)
  7. public @ResponseBody String scheduleVisit(@Valid DoctorVisit doctorvisit, BindingResult result,
  8. HttpServletResponse response){
  9. if(result.hasErrors()){
  10. String errorMessage = "";
  11. response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  12. List<ObjectError> errors = result.getAllErrors();
  13. for( ObjectError e : errors){
  14. errorMessage+= "ERROR: " + e.getDefaultMessage();
  15. }
  16. return errorMessage;
  17. }
  18. else{
  19. return "Validation Successful";
  20. }
  21. }
  22. }

Combining Constraints

Validation annotations can be combined in any suitable way. For instance, to specify a valid reviewRating value between 1 and 5, specify the validation like this :

Annotation:

@Min(value=), @Max(value=)

Data Type:

BigDecimal, BigInteger, byte, short, int, long and the respective wrappers of the primitive types; Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number

Use:

Checks whether the annotated value is higher/lower than or equal to the specified minimum

Reference:

Documentation

Model:

  1. import org.hibernate.validator.constraints.Min;
  2. import org.hibernate.validator.constraints.Max;
  3. public class Review {
  4. //Constraint: Review rating must be between 1 and 5
  5. @Min(1)
  6. @Max(5)
  7. private int reviewRating;
  8. public int getReviewRating() {
  9. return reviewRating;
  10. }
  11. public void setReviewRating(int reviewRating) {
  12. this.reviewRating = reviewRating;
  13. }
  14. ...
  15. }

Controller:

  1. import javax.validation.Valid;
  2. import com.company.app.model.ReviewRating;
  3. @Controller
  4. public class ReviewController {
  5. ...
  6. @RequestMapping(value="/postReview", method=RequestMethod.POST)
  7. public @ResponseBody String postReview(@Valid Review review, BindingResult result,
  8. HttpServletResponse response){
  9. if(result.hasErrors()){
  10. String errorMessage = "";
  11. response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
  12. List<ObjectError> errors = result.getAllErrors();
  13. for( ObjectError e : errors){
  14. errorMessage+= "ERROR: " + e.getDefaultMessage();
  15. }
  16. return errorMessage;
  17. }
  18. else{
  19. return "Validation Successful";
  20. }
  21. }
  22. }

Cascading Constraints

Validating one bean is a good start, but often, beans are nested or in a complete graph of beans. To validate that graph in one go, apply cascading validation with @Valid

Additional Constraints

In addition to providing the complete set of JSR303 constraints, Hibernate Validator also defines some additional constraints for convenience:

  • @CreditCardNumber
  • @EAN
  • @Email
  • @Length
  • @Range
  • @SafeHtml
  • @ScriptAssert
  • @URL

Take a look at this table for the complete list.

Custom Constraints

One of the most powerful features of bean validation is the ability to define your own constraints that go beyond the simple validation offered by built in constraints.

Creating custom constraints is beyond the scope of this guide. Please see this documentation.

Error Messages

It is possible to specify a message ID with the validation annotation, so that error messages are customized :

  1. @Pattern(regexp = "[a-zA-Z0-9 ]", message="article.title.error")
  2. private String articleTitle;

Spring MVC will then look up a message with id article.title.error in a defined MessageSource. More on this documentation.