Red Hat

In Relation To Hibernate Validator

In Relation To Hibernate Validator

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 as well, so it's about time to have a closer look at what you can expect from these updates in relation to Bean Validation and its reference implementation, Hibernate Validator 5.

Over the following weeks, we'll dive into the most exciting new features in a series of blog posts, starting today with the usage of expression language in error messages.

Executive summary

Many users relate the Unified Expression Language (EL) only to JSF and JSP. But it doesn't stop there. Actually, EL has matured over time into an independent language with it's own specification and nice features such as Lambda expressions. It can be used in any application layer, in Java EE as well as Java SE based applications.

Bean Validation 1.1 makes use of EL to offer advanced functionality around constraint violation messages such as conditional messages and customizable message formatting.

Using EL expressions in constraint messages

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 behaviour 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, nicely format values etc. Refer to the EL specification to learn more about the provided functionality and the syntax.

As the {value} expression from the example shows, the Bean Validation 1.0 syntax for referencing attributes is still supported and takes precedence over expression evaluation. So for instance the message ${amount} would be interpolated into something like $50.

Referring to the validated value

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.

Doing some formatting

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.

EL and the classpath

In order to use the expression language feature, you need an EL implementation on your classpath. That's usually the case when running in 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 EL reference implementation and JUEL.

Finally a special tip to all the Tomcat users out there. Hibernate Validator requires at least EL 2.2. This is part of Tomcat 7, so you should be all set there. Tomcat 6 only comes with an EL 2.1 implementation, though. So does this mean you can't experience all the Bean Validation 1.1 goodness on Tomcat 6 then? Luckily not, it just requires a little preparation. Check out the Hibernate Validator FAQ to learn how to update the Tomcat EL libraries.

Trying it out yourself

If you'd like to give the expression language feature a spin, just grab the latest Hibernate Validator release from here. If you work with Maven, Gradle or similar, you can pull it into your project using its GAV coordinates org.hibernate.hibernate-validator.5.0.1.Final. And if you feel adventurous and like playing with the latest bits, you even may build WildFly yourself from its sources. It has been updated to Hibernate Validator 5 a couple of days ago.

The recently revamped reference guide has all the information you need, and we're happy to help you with any questions in the forum.

Today we are happy to announce the 5.0.1.Final release of Hibernate Validator. In case you are wondering what happened with 5.0.0.Final - it has not gone missing. In fact it was released on the 11th of April.

The long story is, that we had to release 5.0.0.Final to meet the Java EE 7 release schedule. At the time the functionality was complete, but documentation was not. Given the amount of changes introduced by Bean Validation 1.1, we felt it was important to wait with the announcement of Hibernate Validator 5 until the documentation is up to scratch. That's the case with 5.0.1.Final. Not only does this release offer a complete Bean Validation 1.1 implementation it also includes an updated online documentation.

The highlights of Hibernate Validator 5 are (with pointers into the freshly baked documentation):

  • Standardized method validation of parameters and return values. This has been a Hibernate Validator 4 specific functionality, but got now standardized as part of Bean Validation 1.1.
  • Integration with Context and Dependency Injection (CDI). There are default ValidatorFactory and Validator instances available and you can now use @Inject in ConstraintValidator implementations out of the box. Requested custom implementations (via validation.xml) of resources like ConstraintValidatorFactory, MessageInterpolator, ParameterNameProvider or TraversableResolver are also provided as managed beans. Last but not least, the CDI integration offers transparent method validation for CDI beans.
  • Group conversion
  • Error message interpolation using EL expressions

We are also planning to create a little blog series introducing these new features in more detail. Stay tuned!

For now have a look at the Getting Started section of the documentation to see what you need to use Hibernate Validator 5. Naturally you will need the new Bean Validation 1.1 dependency, but you will also need an EL implementation - either provided by a container or added to your Java SE environment. Additional migration pointers can also be found in the Hibernate Validator migration guide.

You find the full release notes as usual on Jira. Maven artefacts are on the JBoss Maven repository under the GAV org.hibernate:hibernate-validator:5.0.1.Final and distribution bundles are available on SourceForge.

We are looking forward to get some feedback either on the Hibernate Validator forum or on stackoverflow using the hibernate-validator tag.


Bean Validation, Hibernate Validator (its Reference Implementation) and the Test Compatibility Kit have been handed over to the JCP for what is called the Final Approval Ballot. That's when the expert committee votes for the go / no-go of the specification going final as it is.

We have found a few glitches when working on both the RI and the TCK in the last month but everything is in order now. The biggest visible change for you is that we renamed @ValidateExecutable into @ValidateOnExecution and we added a way to disable method validation entirely via the XML deployment descriptor.

We worked hard to make a stellar TCK. Let's speak numbers: the specification has 549 assertions including 492 testable. We cover 98,8% of them with 1500 tests. Good luck to all future Bean Validation 1.1 implementors :)

Everything is already available for you to use:


PS: If you want regular info on Bean Validation, you should go to the Bean Validation website and enlist to the RSS.

It's my pleasure to announce the availability of Bean Validation TCK 1.1.0.CR1 and Hibernate Validator 5.0.0.CR1.

You can find the TCK

  • as Maven artifact in the JBoss Maven repository under the coordinates org.hibernate.beanvalidation.tck:beanvalidation-tck-tests:1.1.0.CR1 and
  • as distribution bundle (ZIP or TAR) on SourceForge

Hibernate Validator can be retrieved

These releases catch up with the proposed final draft of the Bean Validation 1.1 specification, which was handed over to the JCP just yesterday. Check out the announcement for an overview of what has changed feature-wise since the last Beta releases. We addressed 4 issues in the TCK and 16 issues in Hibernate Validator.

As there shall be no blog post without at least a little bit of source code, let's have a closer look at one of the new features, the XML-based configuration of method constraints, implemented with HV-373.

Let's assume there is a class OrderService like this:

public class OrderService {
    public Order placeOrder(String customerId, Item item, int quantity) {

The following shows an XML constraint mapping for adding method constraints to this class:

<?xml version="1.0" encoding="UTF-8"?>
    xsi:schemaLocation=" validation-mapping-1.1.xsd"

    <bean class="OrderService" ignore-annotations="false">
        <method name="placeOrder" ignore-annotations="true">
            <parameter type="java.lang.String">
                <constraint annotation="javax.validation.constraints.NotNull"/>
                <constraint annotation="javax.validation.constraints.Size">
                    <element name="value">5</element>
            <parameter type="Item">
                <constraint annotation="javax.validation.constraints.NotNull"/>
            <parameter type="int">
                <constraint annotation="javax.validation.constraints.Min">
                    <element name="value">1</element>

The following constraints are added here to the placeOrder() method:

  • The customerId parameter must not be null and must be at least five characters long
  • The item parameter must not be null and it is marked for cascaded validation (equivalent to annotating it with @Valid)
  • The quantity parameter must at least be 1
  • The method return value is marked for cascaded validation

What's next?

The final release of Bean Validation 1.1 is coming soon; in the mean time we'll work on more tests for the TCK, fix bugs as required in Hibernate Validator and polish the documentation.

You want to help? Nothing easier than that, just check out the proposed final draft of the specification and play around with all the new features using Hibernate Validator.

You found a bug? You think the implementation doesn't correctly obey to the specification? That's great! We look forward to your report in our issue tracker. You can also reach us via e-mail or in the commmunity forum.

Hibernate Validator 5.0.0.Alpha2 and 4.3.1.Final

Posted by    |       |    Tagged as Hibernate Validator

Today it's my pleasure to announce the simultaneous release of Hibernate Validator 5.0.0.Alpha2 and 4.3.1.Final.

Hibernate Validator 5

The 5.0.0.Alpha2 release catches up with the public review draft of Bean Validation 1.1 (1.1.0.Beta2). Let's have a closer look at some of the changes in the following.

Method validation

The methods for validating method arguments and return values have been moved from javax.validation.Validator to a new dedicated interface MethodValidator. It is obtained and used like this:

MethodValidator methodValidator = Validation

OrderService myOrderService = ...;
Method placeOrderMethod = ...;
Object[] arguments = ...;

Set<ConstraintViolation<OrderService>> = methodValidator
    .validateParameters(myOrderService, placeOrderMethod, arguments);

Also related to method validation, there is now support for cross-parameter constraints. These come in handy when several parameters of a method or constructor need to be validated together, similar to traditional class-level constraints. The following shows an example:

public void createCalendarEvent(Date start, Date end) {

Opposed to constraints on individual parameters, cross-parameter constraints are specified on the method itself. To make it easy for readers of your code to differentiate cross-parameter constraints from return value constraints, it's recommended to choose a name which clearly expresses the constraint's purpose.

A cross-parameter constraint is defined like this:

@CrossParameterConstraint(validatedBy = ConsistentDateParametersValidator.class)
public @interface ConsistentDateParameters {
    String message() default "{ConsistentDateParameters.message}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

As you can see, this looks very similar to a normal Bean Validation constraint annotation. The only difference is that the @CrossParameterConstraint meta-annotation is used to specify the constraint's validator. The validator must support Object[] as validated type:

public class ConsistentDateParametersValidator implements ConstraintValidator<ConsistentDateParameters, Object[]> {

    public void initialize(ConsistentDateParameters constraintAnnotation) {
        //nothing to do

    public boolean isValid(Object[] value, ConstraintValidatorContext context) {
        if ( value.length != 2 ) {
            throw new IllegalArgumentException( "Unexpected method signature" );

        if ( value[0] == null || value[1] == null ) {
            return true;

        if ( !( value[0] instanceof Date ) || !( value[1] instanceof Date ) ) {
            throw new IllegalArgumentException( "Unexpected method signature" );

        return ( ( Date ) value[0] ).before( ( Date ) value[1] );

As this validator operates on an array of objects representing the method arguments to be validated, it is required to check the number and types of arguments first. The advantage of this approach is that it allows to implement generic cross-parameter constraints which are not specific to one method:

@AreEqual(indexes={0,1}, message="Passwords must be identical")
public void resetPassword(String password, String confirmedPassword) {

The Bean Validation EG also considers a more type-safe approach, which has its own quirks, though. Let us know what would work best for you.

Integration with CDI

One of the big themes in Bean Validation 1.1 is the integration with CDI. The 5.0.0.Alpha2 release brings initial support for this. So it's possible now to have dependencies injected into constraint validator implementations via CDI:

public class OrderNumberValidator implements ConstraintValidator<ValidOrderNumber, String> {

    private OrderValidationService orderValidationService;

    public void initialize(ValidOrderNumber constraintAnnotation) {
        //nothing to do

    public boolean isValid(String value, ConstraintValidatorContext context) {
        return orderValidationService.isValid(value);

But that's not all. When invoking a method on a CDI managed bean which has parameter or return value constraints, automatically an interceptor kicks in, which validates the arguments and return value. If either is invalid, a ConstraintViolationException will be thrown. This protects the method implementation from illegal argument values and the caller from illegal return values. So you'll never have to write code like this again:

public void placeOrder(Item item, int quantity) {
    if(item == null) {
        throw new IllegalArgumentException("Item must not be null");
    if(quantity < 1) {
        throw new IllegalArgumentException("Quantity must be at least 1");
    //actual implementation

Instead this is sufficient:

public void placeOrder(@NotNull Item item, @Min(1) int quantity) {    
    //actual implementation

This does not only simplify the implementation, it also makes sure that the caller knows about the constraints, because they are part of the method's public API.

Group conversion

Finally, there is support for the conversion of the validated groups during cascaded validation, a long standing feature request with the Bean Validation spec. Remember, when annotating an element (e.g. a property or method parameter) with @Valid, validation will be propagated to the referenced object(s).

With help of the new ConvertGroup annotation it is now possible to define which group or sequence on the cascaded element shall be validated when a given group is validated on the parent. Let's look at an example:

//validation groups
public interface Complete extends Default {}
public interface BasicPostal {}
public interface FullPostal extends BasicPostal {}

public class Address {
    @NotNull(groups = BasicPostal.class)
    String street1;

    String street2;

    @Size(groups = BasicPostal.class, min = 3)
    String zipCode = "12";

    @Size(groups = FullPostal.class, max = 2)
    String doorCode = "ABC";
public class User {

        @ConvertGroup(from = Default.class, to = BasicPostal.class),
        @ConvertGroup(from = Complete.class, to = FullPostal.class)
    Set<Address> addresses = new HashSet<>();

When validating a User object with the default group, for the associated addresses the constraints in the BasicPostal group will be validated. When validating a User object with the Complete group, this will lead to a validation of the constraints in the FullPostal group on the user's addresses.

This feature should help with cascaded validations throughout different layers of an application which all define different validation groups.

While these are the major changes of the release, there are some more notable ones, e.g. minor modifications to the metadata API, some changes around ConfigurationSource as well as several bugfixes. Not related to Bean Validation 1.1, we finished the works to clearly separate API, SPI and internal parts of the code base. The changelog has all the details for you.

Hibernate Validator 4.3

While we're heavily working on Hibernate Validator 5 in order to implement revision 1.1 of the Bean Validation spec, we decided to do a maintenance release of Hibernate Validator 4.3, the reference implementation of Bean Validation 1.0.

We fixed a couple of bugs, most notably HV-591. This caused an error when applying the @Email constraint to long strings. Interestingly, this is by far the most reported bug we've had so far in Hibernate Validator with altogether four duplicates. I'm wondering who choses an email address with over 60 characters, but we can validate it now :) Check out the change log for a complete overview of all issues fixed in 4.3.1.

Summing it up

This concludes our tour through the new Hibernate Validator releases.

As usual, both releases can be retrieved from SourceForge (4.3.1.Final, 5.0.0.Alpha2). The Maven coordinates are org.hibernate:hibernate-validator:4.3.1.Final respectively org.hibernate:hibernate-validator:5.0.0.Alpha2. Your feedback is welcome in the forum, the issue tracker and our mailing list. The new features are not described in the Hibernate Validator reference guide yet, so you might be interested in the latest specification draft.

If you have any ideas or proposals around the Bean Validation 1.1 spec, don't hesitate to engage directly with the expert group.

First Alpha release of Hibernate Validator 5

Posted by    |       |    Tagged as Hibernate Validator

Good news for all of you waiting for an early version of Hibernate Validator 5 in order to experiment with the new Bean Validation 1.1 (JSR 349) features. Hibernate Validator 5.0.0.Alpha1 is now available for download in the JBoss Maven Repository under the GAV org.hibernate:hibernate-validator:5.0.0.Alpha1 or via SourceForge.

The focus of the release was the alignment of Hibernate Validator with the first early draft of Bean Validation 1.1 (1.1.0.Alpha1). The Hibernate Validator changelog circles for this reason around HV-571 which served as placeholder for those specification changes. Of course the biggest change was the formalization of method validation, but there are other interesting new features as well. For example:

  • In conjunction with method validation it is worth having a look at the ParameterNameProvider interface which helps to identify the parameter of a failing parameter constraint in the resulting ConstraintViolation. The Path API was also extended to provide additional meta information about a failing constraint. You can get the element descriptor via Path.Node#getElementDescriptor (of course you need to iterate to the leaf node of first). The element discriptors themselves got extended by ConstructorDescriptor, MethodDescriptor, ParameterDescriptor and ReturnValueDescriptor.
  • Support for container injection in ConstraintValidator. Check out the new life cycle methods ValidatorFactory#close and ConstraintValidatorFactory#releaseInstance in this context.
  • Expose settings defined in XML in the Configuration API. Refer to the new interface javax.validation.ConfigurationSource, but be aware that there is a follow up issue (BVAL-292) as well.

The easiest way to find out more about these new interfaces and classes is to have a look at the Hibernate Validator test suite where you will find tests for all the mentioned new features.

There are more proposals which are still under active discussion. Feel free to contribute :-)

Given that this is an early draft there will be further changes to the API. For this reason Hibernate Validator 5.0.0.Alpha1 is not a production release. On the other hand, for integrators and tool developers it makes a lot of sense to have an early evaluation to see whether we are on the right track.


Without further ado, Hibernate Validator 4.3.0.Final is available for download in the JBoss Maven Repository under the GAV org.hibernate:hibernate-validator:4.3.0.Final or via SourceForge.

The changelog for this version does not contain much, so let me summarize the most important changes of Hibernate Validator 4.3

  • The package structure got refactored to separate clearly between API, SPI and internal classes. Doing though we deprecated some classes. Make sure to migrate to the new types when upgrading to 4.3 read more
  • slf4j got replaced by JBoss Logging as the main logging framework read more
  • A bunch of new and improved constraints, e.g. MOD11, CNPJ, CPF and TituloEleitoral read more
  • A bunch of performance and quality improvements, in particular we addressed issues around metadata caching read more
  • The Hibernate Validator Annotation Processor can now be used without any additional dependencies which makes it setup easier read more
  • Hibernate Validator 4.3 requires now a Java 6 or 7 runtime

Please check also the Hibernate Validator Migration Guide.

Last but not least, thanks to everyone who was lending a helping hand during the development of Hibernate Validator 4.3 (in case you wanted to help, but missed out - why not helping by translating the documentation? Join the Hibernate Validator project on Zanata and get started...).


P.S. In case you are waiting for a Validator release which aligns with the first draft of Bean Validation 1.1, have an eye on the JBoss snapshot repository. An initial hibernate-validator-5.0.0-SNAPSHOT won't be far off.

Hibernate Validator 4.3.0.Beta1

Posted by    |       |    Tagged as Hibernate Validator

Moving along the road to a Hibernate Validator 4.3 release I am happy to announce the release of Hibernate Validator 4.3.0.Beta1.

One of our foci this time around was to address existing caching issues. HV-479 addresses the problem that the constraint metadata for a given class would be cached in the so called BeanMetaDataManager without an appropriate eviction policy. In most cases this should not be a problem, but for long running applications with for example hot redeploys it could be. We resolved this issue by introducing SoftLimitMRUCache which has an upper bound for the cached metadata.

HV-564 is another caching related issue. Initially ConstraintValidator instances were only cached if they where created by the Hibernate Validator specific ConstraintValidatorFactoryImpl. Now caching occurs also for custom ConstraintValidatorFactorys.

Two other interesting issues are HV-563 and HV-517. The former allows you to reuse your Configuration instance and call Configuration#buildValidatorFactory() multiple times. The latter introduces the concept of ignoring annotations to the programmatic API. In the XML configuration it has always been possible to do something like this:

        xsi:schemaLocation=" validation-mapping-1.0.xsd">

        <bean class="my.package.MyClass" ignore-annotations="true">
Via the programmatic API this is now possible via:
    // ...
    HibernateValidatorConfiguration configuration = ...
    ConstraintMapping mapping = configuration.createConstraintMapping();
    mapping.type( MyClass.class ).ignoreAllAnnotations();
    // ...
Of course ignoreAllAnnotations() is also available on the property level of the API.

Another important focus was on HV-561. This issue identifies the API methods which will change between Hibernate Validator 4.3 to 5 (as much as we can foresee this at the moment). Causes for these changes are Bean Validation 1.1 and the separation between API/SPI and internal packages. This has already been discussed in the previous release blog. Right now we have two new packages and org.hibernate.validator.spi.resourceloading containing DefaultGroupSequenceProvider and ResourceBundleLocator respectively. The old versions of these interfaces have been deprecated and will be removed in HV 5. On a side note, right now we have the following packages:

Would it make sense to have (by pushing cfg, constraints, group, messageinterpolation, method and resourceloading one level down):
Obviously such a move would break much more client code than the current structure. Let us know what you think.

Last but not least, there are also some news from the Hibernate Validator Annotation Processor which can now be used without any additional dependencies (HV-457). This will make it easier to configure the processor within your build as well as IDE.

Hibernate Validator 4.3.0.Beta1 is available via the JBoss Maven Repository under the GAV org.hibernate:hibernate-validator:4.3.0.Beta1 or via SourceForge. The changelog is available here and make sure to check the Hibernate Validator Migration Guide as well.

Feedback is always welcome via the Validator Forum and the project issue tracker.


A question which came up recently a lot was the question about the release plan for Hibernate Validator 4.3. It is time for an answer.

I used to say that Validator 4.3 will align with Bean Validation 1.1, incorporating any changes required for this specification update. Work on BV 1.1 is still in full swing and it is still time to raise your voice for your long missed validation feature. Check out for more information.

Back to Hibernate Validator though. Over the last few months we incorporated a bunch of useful changes and bug fixes into the code base. For example all string based ConstraintValidators work now on any subclass of CharSequence (HV-502) and the email validator now supports internationalized domain names (HV-472, Java 6 required). Or check out the new generic MOD11 constraint (HV-491) and its application in the new constraints CNPJ, CPF and TituloEleitoral (used for Brazilian individual taxpayer and voting registration numbers). We also have some performance improvements via HV-550 and HV-515.

As you can see quite a bunch of useful changes which we want to release as soon as possible. We also want to offer these improvements for users who don't want to upgrade to Bean Validation 1.1 right away (some of the expected changes will break backwards compatibility with Hibernate Validator 4.2). For this reason we just released Hibernate Validator 4.3.0.Alpha1 with the plan to move to a final release as fast as possible. Two more issues are worth mentioning though: HV-481 and HV-484. The former is the switch to JBoss Logging and the latter is the start of a package refactoring which will (once completed) introduce a clear separation between API/SPI and internal parts on a package level. This change is in accordance with the changes already introduced by the other Hibernate projects. Have a look at the Hibernate Validator Migration Guide to see what these changes imply.

Hibernate Validator 4.3.0.Alpha1 is available via the JBoss Maven Repository under the GAV org.hibernate:hibernate-validator:4.3.0.Alpha1 or via SourceForge. The changelog is available here. Feedback is welcome via the Validator Forum and the issue tracker.

As a result, Hibernate Validator 5 will become the reference implementation of Bean Validation 1.1.

Thanks to all the people suggesting features and reporting bugs. Special thanks to George Gastaldi, Kevin Pollet and Gunnar Morling for your continuous commitment. You guys rock!


So it's official Bean Validation 1.1 has started. It has been voted yes by the JCP expert committee yesterday.

I must admit I'm quite furious about Mark Little, the Red Hat representative and my boss, for forgetting to vote on the ballot. But provided he went on vacations last Friday and has a lot on his plate, I forgive him. You owe me though :)

More seriously, Red Hat is committed to make Bean Validation 1.1 a success and I will spend the next couple of days gathering the expert group members to get started as quickly as possible.

In the mean time and to celebrate, have a look at the official website. The idea behind the website are simple:

  • execute on the promise to run the spec in an open fashion
  • offer regular updates on the work in progress (see the news section)
  • a one time shop for everything Bean Validation related

There are several ways for you to participate in the process. From joining the development mailing list to joining the expert group full blown. Check out the contribution page.

back to top