JavaBean Validation - Validation messages

[Last Updated: Oct 20, 2016]

JavaBean validation specifications require that each constraint annotation must include a 'message' element definition.

This element usage is optional on client side. If not specified a default message resource key is resolved and displayed.

Let's look at @NotNull annotation definition:

 package javax.validation.constraints;

 public @interface NotNull {
	String message() default "{javax.validation.constraints.NotNull.message}";

Followings are the necessary things to know regarding messages:

  • When creating new constraint annotation, the message element must be included. We can specify a default resource key for the message element or we can put a hard-coded message text.
    In case of resource key, it must be within curly brackets {..}
  • Per conventions, the resource key must be fully qualified annotation name appended with '.message', as seen in above @NotNull definition. That means messages should be generic and should not tie to a particular use on the client side.
  • Client can specify and override a new 'message' on a particular annotation usage.
    @NotNull(message="name must not be null to be valid")
    String name;

    In above snippet, client can also use a new resource key instead. In that case we have to use curly brackets:

  • If we want to override default messages with our resource keys or even the default keys, then the resource files must be in classpath and should be named as '' i.e. they should always start with 'ValidationMessages' then with underscore separated language code (locale variations). This is the default behavior which can be modified by implementing javax.validation.MessageInterpolator

Use of Expression language

This specification supports Unified Expression Language (JSR 341) for evaluating dynamic expression in the validation messages that's the reason we have to include 'javax.el-api' and it's implementation dependencies in our projects.

The values substitution from constraint annotation element declarations:

Within the messages, constraint annotation element values can be referenced as '{theElementName}'.

For example @Min(5), we can use message: 'The min value must be {value}'.
Here {value} will be replace with 5.

The expression can be evaluated for inline messages or in resource bundle files as well

Here are few examples from the Hibernate message resource implementation,

javax.validation.constraints.DecimalMax.message  = must be less than ${inclusive == true ? 'or equal to ' : ''}{value}
javax.validation.constraints.DecimalMin.message  = must be greater than ${inclusive == true ? 'or equal to ' : ''}{value}
javax.validation.constraints.Digits.message      = numeric value out of bounds (<{integer} digits>.<{fraction} digits> expected)
javax.validation.constraints.Max.message         = must be less than or equal to {value}
javax.validation.constraints.Min.message         = must be greater than or equal to {value}
javax.validation.constraints.Pattern.message     = must match "{regexp}"
javax.validation.constraints.Size.message        = size must be between {min} and {max}

Using ${validatedValue}

This is the the currently validated value (property, bean, method parameter etc).

For example:

public class TestBean {

    @Size(min = 5, message ="The name '${validatedValue}' must be at least {min}" +
                        " characters long. Length found : ${validatedValue.length()}")
    private String name;

   // getters and setters

Now if we populate our bean like this and run the validations:

public static void main (String[] args) {
     TestBean testBean = new TestBean();

     Validator validator = getValidator();


The name 'Mike' must be at least 5 characters long. Length found : 4

Example Project

These examples demonstrate the use of external resource bundle along with expression language usage.

Dependencies and Technologies Used:

  • Hibernate Validator Engine 5.2.4.Final: Hibernate's Bean Validation (JSR-303) reference implementation.
  • Expression Language API 2.2 2.2.4
  • Expression Language 2.2 Implementation 2.2.4
  • JDK 1.8
  • Maven 3.0.4

Validation Messages Select All Download
  • validation-messages
    • src
      • main
        • java
          • com
            • logicbig
              • example
          • resources

    See Also