Red Hat

In Relation To Bean Validation

In Relation To Bean Validation

After some time in the making, we are happy to announce the first Hibernate Validator release of the 5.2 series - 5.2.0.Alpha1. This release focuses mainly on Java 8 support, but we will get to this in a bit.

First a big thank you to Khalid Alqinyah who, as part of a Google Summer of Code project, implemented many of these new features.

So what's in it for you?

Java 8 support

Note: Java 8 is not a requirement for Hibernate Validator 5.2. Hibernate Validator is still backward compatible with Java 6. Java 8 specific features are only enabled when a Java 8 runtime is detected.

First off, the Java 8 date/time data types (JSR 310) are supported and can be validated via @Past and @Future. Also Optional and JavaFX types are supported via an improved ValidatedValueUnwrapper. ValidatedValueUnwrapper was already introduced in Validator 5.1, but works now in a more transparent way. Upon validation all registered ValidatedValueUnwrapper instances are checked. If a handler supports the validated type its handleValidatedValue method is called, provided that there exists no matching ConstraintValidator for the wrapper itself. This is best explained with an example:

@Size(min = 3) // the @Size constraint can only apply to the string value which gets automatically validated
private Optional<String> firstName = Optional.of( "John" );

@UnwrapValidatedValue(false) // Use @UnwrapValidatedValue(false) to ensure the wrapper itself is validated
private Optional<String> lastName = Optional.of( "Doe" );
Another Java 8 related feature is the ability to use type annotations on Iterable instances. Something like this:
private List<@AcmeEmail String> emails;
Note that the example is not using Hibernate Validator's @Email. Neither Bean Validation's built-in constraints nor Hibernate Validator specific ones, can be used. The simple reason is that these constraints are missing java.lang.annotation.ElementType.TYPE_USE in their definition and it cannot be added in a backwards compatible way. At the moment we have not yet decided what to do. Should we make Java 8 a requirement for Validator 5.2 or should we somehow provide JVM specific artifacts? What do you think? Right now we want to keep the options open and see which path Bean Validation 1.2 and other Java EE 8 standards are taking. For now this feature is limited to custom constraints where you can add the required ElementType yourself.

Last but not least, in the Java 8 driven feature list, is ReflectionParameterNameProvider. This new ParameterNameProvider makes use of enhancements in the Java 8 reflection API and reports actual parameter names instead of the generic arg0, arg1, etc. A requirement for this provider to work is that the sources are compiled with the -parameters compiler option. Refer to the docs to see how to configure a custom ParameterNameProvider.

What else?

Here are a couple of more highlights from this release:

ConstraintDefinitionContributor and ServiceLoader for constraint definitions

The Bean Bean Validation specification allows to register new constraint definitions via XML mapping files. For example:

<constraint-definition annotation="org.hibernate.validator.constraints.URL">
  <validated-by include-existing-validators="false">

We offer now two more ways of contributing constraint definitions. The first is programmatically via the ConstraintDefinitionContributor SPI. The above example would look like:

HibernateValidatorConfiguration configuration = Validation
        .byProvider( HibernateValidator.class )

        new ConstraintDefinitionContributor() {
                public void collectConstraintDefinitions(ConstraintDefinitionBuilder builder) {
                        builder.constraint( URL.class )
                                .includeExistingValidators( false )
                                .validatedBy( RegexpURLValidator.class );

By the way, org.hibernate.validator.constraintvalidators.RegexpURLValidator is not a made up class. It is another new feature (HV-920) which allows to configure a regular expression based validator for the @URL constraint.

Back to constraint definition though. The second way to contribute constraint definitions is via the Java ServiceLoader mechanism. Just add META-INF/services/javax.validation.ConstraintValidator to your artifact listing the fully qualified classnames of your constraint validator classes (one per line). This mechanism works fine for adding constraint definitions for new types. You cannot as possible in XML or via the ConstraintDefinitionContributor disable default definitions.


Hibernate Validator requires per default an implementation of the Unified EL to be available. For environments where you cannot or do not want to provide an EL implementation, we offer now a non EL based message interpolator - org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator.

Warning: Constraint messages containing EL expressions will be returned un-interpolated!

These were just the highlights. In total a whopping 40 issues got resolved. Be one of the early adopters and get the Maven artifacts from the JBoss Maven repository (GAV org.hibernate:hibernate-validator:5.2.Alpha1) or the SourceForge distribution bundles.

Simultaneously with the 5.2 alpha release we published a 5.1 maintenance release. We accidentally broke Java 6 backwards compatibility in 5.1.2.Final by using Collections#emptyIterator(). This is corrected in 5.1.3.Final and Java 6 compatibility is restored.

The second bug fixed in 5.1.3.Final is HV-930 where constraints were not validated when the internal weak reference cache of Hibernate Validator got partly invalidated due to memory pressure.

The full 5.1.3.Final change log can be found here. Maven artifacts are on the JBoss Maven repository under the GAV org.hibernate:hibernate-validator:5.1.3.Final and distribution bundles are available on SourceForge.

If you are using a 5.1 version of Validator it is highly recommended to upgrade to 5.1.3.Final. Or why not giving the 5.2 Alpha version a go?

Feedback and questions are welcome via the Hibernate Validator forum or on stackoverflow using the hibernate-validator tag.


This post is about validation, Bean Validation specifically. And the what it solves. It is a reaction to a post by Julien Tournay which basically claims - if I sum it up - that:

  • Scala is faster than Java (he is coming from far far away on that one - du diable vauvert as we say in French)
  • Bean Validation is kind of crap
  • The new Play Unified Validation API is awesome

I usually am old and wise enough not to answer these kind of posts. But I want to feel the blood of my youth again damn it! After all I am from an era when The Server Side was all the rage, trolls had real teeth, things were black or white. That was good fun.

Why the You missed the point like Mars Climate Orbiter title? With a sensationalist title like Scala is faster than Java, I had to step up my game. Plus Mars Climate Orbiter missed Mars due to a conversion error and we will talk about conversion today.

I won't refute things point by point but rather highlight a few fundamental misunderstandings and explain why things are like they are in Bean Validation and why it makes sense.

Java was limiting

IMHO, @emmanuelbernard a créer son API avec les outils a sa disposition - @skaalf
IMHO, @emmanuelbernard has created his API with the tools he had at his disposal - @skaalf

We certainly pushed the boundaries of Java when both CDI and Bean Validation were designed and I wished I had more freedom here and there. But no Bean Validation is like it is because that's the most natural way validation is expressed in the Java ecosystem for what we wanted to achieve. It is no good to offer something that does not fit into the ecosystem.

For example, in Java, people use mutable objects. Mutable believe it or not is not a swear word in this language. My understanding is that Play Unified Validation API makes use of Scala's community incline for immutability.

Validation, conversion and marshalling

In the use case Julien takes as an example, a JSON string is unmarshalled, conversion is applied (for dates - darn JSON) and then values are validated. He considers it weird that Bean Validation only does the latter and finds the flow wrong.

We kept this separation on purpose. The expert group vastly agreed that Bean Validation was not in the business of conversion and that these steps ((un)marshalling, conversion, validation) should be separated. Here is a key reason:

  • marshalling and conversions are only at the Java boundaries (Web frameworks, services enpoints, datastores enpoints, etc)
  • validation happens both at these boundaries but also at key lifecycle events within the Java boundaries

Conceptually, separating validation from the rest makes a lot of sense to enable technology composition and avoid repetitions - more on that latter point later. What is important is that for a given boundary, they are properly integrated. It's not unlike inlining in compilation.

Bean Validation is in the business of not being called

One key point in the design of Bean Validation is that it has been built to be integrated within a cohesive stack more than to be used individually.

JPA transparently calls Bean Validation on your objects at the right time. JSF calls Bean Validation transparently before populating the beans. JAX-RS calls Bean Validation on the inbound and outbound resources transparently. Note that these three technologies do address the marshalling and conversion problem already. That's their job.

So the key is that an application rarely has to call the Bean Validation API. I consider it a failure or an unfinished work when it has to.

If you need to explicitly validate some piece of data in a fire and forget way, Bean Validation might not be the best tool. And that's OK.

Back to the JSON case. When the JSON Binding spec will be out, we will have the same integration that is currently present in Play Unified parsing, conversion and validation API (it could also be done today in Jackson, I'm not sure what extension points this library offers). While the three layers marshalling / conversion / validation will be conceptually separated - and I'm sure will report different types of error for better tracking - the implementation will use some specific APIs of Bean Validation to inline validation with the unmarshalling and conversion. That API exists BTW, it is Validator.validateValue which lets you validate a value without creating the POJO associated. It is used by web frameworks already. Pretty much what Play Unified Validation API does.

As for JAX-B and XML binding, well let's say that there is an X in it and that it's not safe for children. More seriously, we have integration plans with mapping between the XSD and the Bean Validation constraints but we haven't got around to do it yet.

Bean Validation is in the business of declaring constraints once

From what I see of the Play Unified Validation API, you put the declaration / implementation of the validation next the marshalling logic. In other words you cannot share the constraint declaration between different marshalling operations or even between object transformations.

Bean Validation has been designed to let the user declare the constraints once and have them validated across the whole stack. From the web form and service entry points down to the database input/output and schema definition. Some even use our metadata facility to propagate the constraints up to the client side (JavaScript).

And that's future proof, when we add JSON-B support, boom the constraints already declared are used automatically and for free.


Bean Validation cannot be understood if you take it in isolation. It is useful and works in isolation for sure but it shines when integrated in a platform from top to bottom. We did and keep doing it in Java EE but we also make sure to keep our APIs and SPIs open for other platforms to do the same. Spring famously has been doing some of it.

Let's mention a few key features of Bean Validation that are not addressed at all in Play's approach:

  • i18n
  • constraint inheritance
  • method validation
  • custom and context sensitive programmatic error report
  • partially valid object graph - yes that's important in a mutable world
  • etc

Even a few of these would make Play's stuff much much different.

Now with this context properly set, if you read back Julien's complaints about Bean Validation (especially about they design), they fall one by one pretty much. I have to admit their composition approach is much nicer than Bean Validation's which relies on annotated annotations. That's the main thing I miss.

Design is choice. Without knowledge to the designer's choices, you can too easily misunderstand her design and motives. Julien has been comparing Apples with Oranges, which is ironic for someone working on one of the most type-safe language out there :o)

But it's good that more people take data validation holistically and seriously and step up the game. Less work for app developers, safer apps, happier customers. Judging by the location, I could even share some thoughts over a few rounds of whisky with Julien :)


Emmanuel is headed to JavaOne, where you can see his hands-on presentations: live on stage coding showing the latest features of Hibernate Search and Bean Validation. It's a unique experience to see how easy it is to get started with these technologies, and also what powerful features they can provide you in just one hour coding.

Hibernate Search: Geolocalized Search in Java EE 7 in 59 Minutes

Full link: Geolocalized Search in Java EE 7 in 59 Minutes with Hibernate Search [BOF3307]


Search is passé; we need Foursquare-style location and should let people search in specific vicinities. And no, you don’t have to leave Java or JavaEE to make this a breeze. This session shows you how to boost your existing applications by easily adding full-text search, spatial search, faceting, and even all at the same time! Faceted results return the list of results as well as their count by category—price range, brand, colour, and so on. This session takes an existing JavaEE7–based application and adds search services via Hibernate Search. It favours code and step-by-step IDE work over slides.
  • Presenter: Emmanuel Bernard
  • Location Parc 55 - Mission
  • Time: Monday, Sep 23 7:30 PM - 8:15 PM

Bean Validation: What Does It Look Like in Practice?

Full link: Bean Validation: What Does It Look Like in Practice? [CON3368]


Java EE 7 is a very rich environment. This session takes you on a practical code-driven Bean Validation walk-through: how to use it in your applications and what not to do—all with an example-driven approach. The presentation gradually adds constraints and validations to an existing application and examines many features, both old and new, including constraint declaration, custom constraint, method validation, EL-based message interpolation, JAX-RS integration, and many more. It spends as much time as possible in the IDE. No previous knowledge of Bean Validation is required.
  • Presenter: Emmanuel Bernard
  • Location: Parc 55 - Cyril Magnin II/III
  • Time: Wednesday, Sep 25 11:30 AM - 12:30 PM

Other JBoss technologies at JavaOne

There are lots of speakers from the JBoss community at JavaOne, see the dedicated website!

With the release of Hibernate Validator 5.1.0.Alpha1 just out, it is time to pick up on the Bean Validation 1.1 spotlight series and cast a light onto method validation. Long time Hibernate Validator users know that method validation is part of Validator since version 4.2, however only as a provider specific featue. Bean Validation 1.1 makes method validation now part of the specification.

But what is method validation? Method validation is the ability to place constraint annotations onto methods or constructors and/or their parameters. Here is an example:

public class User {
     public User(@NotNull @Size(max = 40) String firstName, @NotNull @Size(max = 40) String lastName) {
        // ...

     public Order placeOrder(@NotNull @Valid Item item) {
          // ...

     public void resetPassword( @NotNull String password, @NotNull String passwordConfirmation) {
          // ...

     // ...

The constraints describe that whenever the constructor of User is called, firstName and lastName cannot be null and neither can exceed 40 characters. Also, whenever the user places an order, the provided Item instance cannot be null and must be valid. Valid in this context means that the instance itself passes the validation of all its property (constraints placed on fields and getters) and class level constraints. The returned Order instance of the placeOrder() call is a non null instance which also passes all bean constrains for this type. Last but not least, if the user resets his password, the new password and the password confirmation cannot be null and they have to match. The latter is expressed via a so called cross parameter constraint - @PasswordMatch.

Overall, the shown constraints define the pre- and postconditions for a given method or constructor call. This is commonly known as programming by contract which allows to make the specification of the these constraints part of the method. It also avoids code duplication, since these checks don't have to be implemented redundantly in the body of the methods.

But how do these constraints get validated then? Bean Validation offers for this purpose ExecutableValidator which can be retrieved from a Validator instance via Validator.forExecutables(). This ExecutableValidator offers the methods to validate method/constructor parameters and return values. This in itself, however, is not very helpful for an application developer. She would have to write the required code to handle the validation herself which is not a trivial task. Instead the intention is that frameworks and libraries provide the integration for the application developer via some sort of AOP, interceptor or proxy based approach. That way, method validation occurs transparently upon invocation of constrained methods or constructors, throwing a ConstraintViolationException whenever one more more constraints are violated. An example of this type of integration is the Java EE 7 framework.

In Java EE 7 all CDI managed beans are automatically method validated. All you have to do is to place constraints on methods or constructors and their parameters. CDI will then, via its interceptor capabilities, evaluate all method validation constraints. In this context it is important to know that Bean Validation does not validate getters (method name starts with get, has a return type and no parameters or starts with is, is returning boolean and has no parameters) per default. This is to avoid conflicts with the validation of bean constraints. This behaviour can be configured via the use of @ValidateOnExecution or in validation.xml using default-validated-executable-types. The specification contains all the details and also gives some examples.

Last but not least, another caveat. When using method validation constraints within class hierarchies, the specification demands that the Liskov substitution principle holds. Formally this means that a method's preconditions (as represented by parameter constraints) must not be strengthened and its postconditions (as represented by return value constraints) must not be weakened in sub-types. Concretely it implies that in sub-types no parameter constraints can be declared on overridden or implemented methods. Also parameters cannot be marked for cascaded validation. Instead, all parameter constraints must be defined at the method's root within the hierarchy. The Bean Validation implementation will throw a ConstraintDeclarationException if the Liskov substitution principle is violated. The complete set of rules can be found in Method constraints in inheritance hierarchies of the specification.

I hope this blog helped to shine some light on the biggest new feature of Bean Validation 1.1 - method validation. If you have questions, leave a comment, contact us via the forum or chat to us in IRC.

Happy validating!

P.S. We will talk about the changes to the metadata and javax.validation.Path API related to method validation in another post. We also will have a closer look at the details of implementing cross parameter constraints. Stay tuned.

It's my pleasure to announce the first alpha release of Hibernate Validator 5.1. This release brings you several new features based on top of the Bean Validation 1.1 APIs, substantial performance improvements as well as some bug fixes.

As usual, you can obtain this release either as distribution bundle (ZIP or TAR.GZ) from SourceForge or retrieve it using your preferred dependency management tool under the GAV coordinates org.hibernate:hibernate-validator:5.1.0.Alpha1. The binaries have been pushed to the JBoss Maven repository and should soon be synched to Maven Central as well.

What's in it?

The features added in this release are centered around the new APIs and functionality provided by Bean Validation 1.1, such as method validation and expression based message interpolation. Let's have a closer look at some of them.

With HV-714 we added a new constraint, @ParameterScriptAssert which allows to validate the parameters of a method or constructor using a script expression:

@ParametersScriptAssert(script = "arg0.before(arg1)", lang = "javascript")
public void createCalendarEvent(Date start, Date end, String title) { ... }

Similar to @ScriptAssert (which applies to the class level) this constraint can be used with every scripting language for which a JSR 223 compatible engine exists. You can choose between a wide variety of options such as JavaScript (for which the JDK provides an engine out of the box), Groovy, JRuby and many others.

As shown in the example, the names arg0, arg1 etc. are used by default to refer to the parameters of the validated method or constructor. This does not read very well, but unfortunately Java doesn't provide a standardized way to obtain parameter names at runtime (this will change with Java 8 where parameter names can be accessed via reflection).

To address this issue, Bean Validation defines an SPI which allows to plug in custom parameter name providers. Hibernate Validator offers now an implementation of that SPI (HV-802) which is based on the ParaNamer project. ParaNamer is a nice little library which provides several ways for obtaining parameter names at runtime:

  • based on debug symbols created by the Java compiler,
  • constants with the parameter names woven into the bytecode in a post-compile step or
  • annotations such as the @Named annotation from JSR 330.

To use this parameter name provider, add the ParaNamer library to the classpath and configure the provider like this when bootstrapping a validator:

Validator validator = Validation.byDefaultProvider()
    .parameterNameProvider( new ParanamerParameterNameProvider() )

With the parameter name provider configured, you can refer to the parameters using their actual names from within the @ParameterScriptAssert constraint (the names will also be used by constraint violations for invalid parameter constraints):

@ParametersScriptAssert(script = "start.before(end)", lang = "javascript")
public void createCalendarEvent(Date start, Date end, String title) { ... }

Refer to the ParaNamer documentation to learn more about the different ways it provides for accessing parameter names.

Message interpolation

Another nice new feature is an extension of the ConstraintValidatorContext API which allows to add arbitrary objects to constraint violation messages (HV-701). As an example, let's consider this custom validator for the @Future constraint:

public class MyFutureValidator implements ConstraintValidator<Future, Date> {

    public void initialize(Future constraintAnnotation) {}

    public boolean isValid(Date value, ConstraintValidatorContext context) {
        if ( value == null ) { return true; }

        Date now = GregorianCalendar.getInstance().getTime();

        if ( value.before( now ) ) {
            HibernateConstraintValidatorContext hibernateContext =
                context.unwrap( HibernateConstraintValidatorContext.class );

            hibernateContext.addExpressionVariable( "now", now )
                    "Must be after ${formatter.format( '%1$te.%1$tm.%1$tY %1$tH:%1$tM', now ) }"

            return false;

        return true;

Instead of just using "Must be in the future" as constraint violation message, this validator adds the current time to the message. For that purpose an expression variable with the name "now" is added to the validation context, holding a Date object representing the current time. Using the variable name, it can be accessed from within the violation message and formatted as shown in the example.

Performance improvements

Besides adding new functionality, we also worked hard to make sure that Hibernate Validator gives you the performance you deserve. Throughout extensive profiling sessions we identified and addressed several performance bottlenecks, e.g. around message interpolation (HV-637). Performance tuning - with respect to memory consumption as well as execution speed - is an ongoing effort and you can look forward to further improvements in that area in the next releases.

This concludes our tour through the new features of Hibernate Validator 5.1.0.Alpha1. You can find the complete list of all fixed issues in the release notes. The reference guide describes all added functionality in detail.

Let us know how you like the new release by adding a comment or posting to the forum. If you have found a bug be sure to file a JIRA issue for it. Or, even better, fork the code base and submit a pull request with the required fix. To discuss any development related issues, just send a message to the hibernate-dev list.

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.

Slides from Bean Validation talk available

Posted by Gunnar Morling    |       |    Tagged as Bean Validation Events

Recently I had the chance to give a talk on Bean Validation 1.1 at Berlin Expert Days (BED-Con), a nice mid-sized conference (2 days, 500 attendees) hosted at Freie Universität in Berlin. As in the last years, BED-Con was a great experience with awesome people and many insightful talks in the fields of Java EE, NoSQL, Continuous Delivery etc. I really can recommend this event which is planned to take place next year again.

My talk on Bean Validation went very well and I got lots of questions on the new functionality. In particular the possibility to use constraints on method parameters and return values (method validation) seems to be a helpful feature for many. You can find my slides which discuss the new features on the conference web site (in German, though).

I also used the opportunity to listen to some talks around client side web applications using HTML 5 and REST. There's a lot of activity going on in this field right now, and it appears like a new framework is released every day.

An interesting question to me is how Bean Validation as Java based technology fits into this picture. Bean Validation provides an API for retrieving constraint meta-data from models which could be used to perform a client-side validation of data entered by the user. It would surely be interesting to see how this could be leveraged to expose constraint meta-data e.g. via a REST service and use it on the client with frameworks such as AngularJS. Maybe this is even done by some frameworks already?

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.

Bean Validation 1.1 update and first draft

Posted by Emmanuel Bernard    |       |    Tagged as Bean Validation

I have been quite quiet of late on what I have been busy with. One thing has been working on is Bean Validation 1.1, the version targeted for Java EE 7.

The Bean validation expert group has just released the first draft of what will become Bean Validation 1.1, go grab it and don't forget to give us your feedback!

If you are interested in news about Bean Validation in general, I highly encourage you to subscribe to the news feed of

back to top