Skip to content

Instantly share code, notes, and snippets.

@emmanuelbernard
Forked from gunnarmorling/bv_11_spotlight_el.md
Last active December 19, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emmanuelbernard/5927643 to your computer and use it in GitHub Desktop.
Save emmanuelbernard/5927643 to your computer and use it in GitHub Desktop.

Bean Validation 1.1 Feature Spotlight - Expression Language

It has been a couple of weeks since Bean Validation 1.1 has gone final. In the mean time, the Java EE 7 platform spec has been finalized, so it's about time to have a closer look at what you can expect from this update to the Bean Validation spec and its reference implementation, Hibernate Validator 5. Over the following weeks, we'll discuss the most exciting new features in a series of blog posts, starting today with the usage of expression language in error messages.

One of the lesser known facts about Java EE is that the Unified Expression Language (UEL) can not only be used in JSF or JSP pages, but actually in any application layer. Bean Validation leverages this to support the creation of constraint violation messages in a dynamic manner.

As an example, let's take a look at the built-in DecimalMax constraint. As of Bean Validation 1.1, this constraint has a new flag named inclusive which specifies whether the given maximum value is inclusive or not. Depending on the flag's value, the constraint's error message should either be "must be less than {value}" or "must be less than or equal to {value}".

This kind of behavior was not easily achievable in Bean Validation 1.0 but it is straight-forward using an EL expression which conditionally adds the "or equal to" part:

"must be less than ${inclusive == true ? 'or equal to ' : ''}{value}"

EL expressions are given in the form ${expression}. You can use them to implement conditional logic as in the example, perform calculations and much more. EL 3.0 even has support for lambda expressions. Refer to the EL specification for the complete syntax.

As shown in the example, the Bean Validation 1.0 syntax for attribute references ({attribute}) is still supported and takes precedence over expression evaluation. So for instance the message "${amount}" would be interpolated into something like "$50".

Besides all attributes of the validated constraint (such as inclusive) you can access the value to which the constraint is applied using the name validatedValue as shown in the following example:

@ValidCustomer( message = "Not a valid customer: ${validatedValue.getName()}" )
public class Customer {

    //...

    public String getName() {
        return name;
    }
}

Here, a violation of the @ValidCustomer constraint would produce a message such as "Not a valid customer: Bob".

Finally, a helper for formatting strings is exposed under the name formatter, providing a var-args method format(String format, Object... args) which exactly behaves like java.util.Formatter.format(String format, Object... args). This comes in handy if you e.g. want to format number values in a special way:

public class Order {

    @DecimalMin(value="20.00", message="Order value too low: € ${formatter.format('%08.2f', validatedValue)}")
    private final BigDecimal value;

    //...
}

The shown format expression causes the value to be padded with leading zeros, so if the @DecimalMin constraint is violated, you would get a message such as "Order value too low: € 00017.89".

Note that in order to use the expression language feature, you need an UEL implementation on your classpath. That's usually the case when running on a Java EE container such as WildFly but you'll have to add an implementation by yourself if your application runs in a plain Java SE environment. Two implementations known to work with Hibernate Validator are the UEL reference implementation and JUEL.

If you'd like to give the expression language feature a spin, just grab the latest Hibernate Validator release from here. The recently revamped reference guide has all the information you need, and we're happy to help you with any questions in the forum.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment