Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage Articles Interview: Emmanuel Bernard on the Bean Validation specification

Interview: Emmanuel Bernard on the Bean Validation specification

This item in japanese

Following on from a previous article on the early draft of the Bean Validation framework, InfoQ sat down with Emmanuel Bernard to learn more about the proposal and the community involvement the expert group is seeking.

InfoQ: I was expecting that the specification would support some sort of XML model as well as annotations but it doesn't seem to. Is this something you've moved away from?

Emmanuel Bernard (EB): The specification will support an XML model. However we wanted to initially settle the feature set and the meta model before going through the process of working on the XML descriptor. Annotations can be used as the internal model in a JSR 303 Bean Validation implementation. Once we have defined the annotations model correctly, XML should be close to a transposition, just another language.

InfoQ: Do you plan to support a hierarchy of error messages - so I have a standard way of displaying a generic error message that I can override with a page/screen specific error message if I want to?

EB: I am not sure I understand your question but let me try to answer from two angles
a) The Bean Validation specification lets you externalize and internationalize the constraint error messages through a classic file system based ResourceBundle localization. A constraint can declare a key rather than using a "hardcoded" message.

@Length(max = 50, message="{}")
String name;

## French resourceBundle =
Le nom ne peut dépasser {max} caractères

To go beyond this model and provide a natural integration with application or presentation frameworks (web framework for example), the message resolution strategy is entirely pluggable.

Lets take an example: Web Beans promotes the idea of contextual components (event, page, request, conversation, business process for example). Web Beans can use Bean Validation and plug in its context aware message resolution strategy: an error message containing contextual expressions will then be resolved.

Another example. Wicket resource bundle resolution is hierarchically defined. It first tries to find the key in the panel resource file, then the page resource file and finally the application resource file. Wicket can provide its own message resolution implementation following this pattern.

In both cases, the contextual information is critical to provide a suitable error message. The Bean Validation caller is in a better position to know this context: by providing a custom message resolution implementation, it offers the user a natural and homogenous experience while still delegating the validation work to Bean Validations.

b) On a more philosophical note, I wonder why you would need to change a constraint message on a specific page? Often a constraint message needs to be "customized" in a particular context because what appears to be one constraint is indeed two different constraints applied in different contexts. The Bean Validation specification provides a mechanism to describe contextual constraints. Each constraint belongs to one or more groups. When validating an object, a list of groups can be provided to select the context in which the validation is applied. I described some of the use cases for groups in a blog entry.

InfoQ: One common problem with internationalization and validation is where the validation rules may be different between locales. For example an alphanumeric test may vary. How is this handled?

EB: What I have seen generally is constraint rules depending on a property value more than on the actual locale. To take the canonical example of an address, the zip code or the phone number constraints vary depending on the country this address belongs to.

Some constraints will not change (not null, maximum length in the database), but some will vary with the country. The specification addresses this problem today by providing class level constraints. A class level constraint has access to the bean instance rather than one of its properties and applies some constraint logic based on several properties. Phone number validation logic would apply different rules for France and the USA, it might even call an external service for Canadian phone numbers based on an existing database rather than formatting rules.

This is an interesting problem and people have different takes on what the solution should be. The class-level approach offers the greatest flexibility and keeps the specification simple. The debate is still raging though: if you have an opinion, go to and speak up :)

InfoQ: Can we use Expression Language for manipulating error messages and/or do we have insert points for messages (enter a number between {x} and {y})?

EB: Yes the default message resolution strategy permits the injection of constraint parameters.

@Length(max = 50, message="{}")
String name; = Names must not be longer than {max} characters

will result in the message: Names must not be longer than 50 characters.

But this is clearly an area where the expert group is looking for feedback and proposals. Some discussions have started already on the Bean Validation feedback forum to provide additional contextual information.

Also as I described previously, a custom message resolution strategy can be provided to the Bean Validation provider: this is key to providing a natural integration with existing web and application frameworks. I think the application and web frameworks have way more information at their disposal than the Bean Validation framework and thus can provide a much better variable interpolation and expression language resolution.

InfoQ: Do you plan to support hyperlinks within error messages and, if so, how are localization issues handled (the placement of the link may be
different in different locales for example)?

EB: What you are describing is highly dependent on the presentation framework. A custom message resolution strategy provided by the presentation framework is perfect to handle such situations, as the presentation framework has all the contextual knowledge (URL root, parameters to pass along and so on).

InfoQ: How will multi-language scenarios be handled between tiers? For example if a back-end system generates an error in one language (say English) but I need to display it to the user in another language such as Cantonese.

EB: This is a very interesting question and unfortunately not one I have all the keys to answer as it involves the Java EE platform as a whole and not just Bean Validation.
The back-end system should not generate the error message in English if it is expected to be read in Cantonese. While the specification does not describe it yet, the expert group expects to provide the ability to customize the locale used for a given validation invocation (probably through a thread based propagation model). The application framework will be responsible for passing the locale along from the client side to the server side.

As you can see, the integration between the application frameworks (the callers) and Bean Validation will be key to providing a neat user experience. Unfortunately (or fortunately), this JSR focuses on constraint declarations and validations. The expert groups are however aware of the big picture and we try as much as possible to provide the necessary extensions and integration points to enable consumers to integrate properly.

InfoQ: Ideally I'd like to be able to handle all my validation (say from JavaScript, in the application layer, for the database) using the same framework. How close does the current specification get to that objective?

EB: What is vital in my opinion is the ability to share the same constraint definitions across these heterogeneous layers. If the same validation framework can be reused, even better.

Bean Validation is layer agnostic, all Java layers from the presentation layer down to the DAO layer can simply delegate constraint validations to the Bean Validation runtime. Lets take a few examples:

  • Java Persistence can call Bean Validation every time an entity is either added to or updated in the database
  • A business component can call Bean Validation on a set of data before applying the core business logic
  • The presentation layer can call the validation logic on the data provided by a form before passing it to the domain model
  • Bean Validation in this context is the validation runtime engine called by various pieces of your architecture. Because the constraints are placed on the domain model classes and shared by all layers, the same validation applies across the board.

It gets more complicated and interesting for layers that go beyond Java. The database is a good example. Some constraints make perfect sense in the database schema (not null, length and so on). The Bean Validation specification exposes some of the constraints' basic metadata information through a metadata request API. Java Persistence can hook into this API, extract useful information and apply some constraints to the database schema.

On the presentation side, and specifically in a web application, some constraints can be applied by JavaScript code. It reduces the number of roundtrips to the server and provides a better user experience through early error feedback. Two approaches are possible in this situation. The presentation widget (say a JSF component) can extract the constraint metadata from the Bean Validation request API and apply the same logic in JavaScript. Of course not all constraints can be expressed by this model. Some of them though will be applied on the client side. The beauty of this approach is that both the client and server side stay transparently consistent as they both share the constraint declarations from the domain model. While we do not reuse the actual constraint implementation, the metadata API offers some ways to extract the constraint definition and reuse it. The second approach is to use a GWT-like approach: the Java code is converted into JavaScript: the same implementation logic is then shared between the client side and the server side.

InfoQ: OK - so suppose I have a phone number field in a web application. The field is required, has a max length of 40 characters, and accepts alphanumeric values only. I want to use JavaScript to check the field length on the web side. On the database side I also have the field defined as a CHAR40. If I want to look up the constraint validations from the web tier how do I do this and what do I get back? Do you see this working in the same way for JPA 2?

EB: What you are describing is basically exporting the constraints beyond the boundaries of Java. To make that happen, the framework linking the Java world and the web/JavaScript work needs to:

  • know the link between a web form input and a domain model property
  • have access to the constraint descriptions

The first point is the role of the linking framework. It could happen by inspecting the expression language (in JSF for example), it could happen because the framework speaks "Java" (in Wicket for example).

The second point happens because from a property, the linking framework can query the Bean Validation's metadata API and receive the list of constraints. Each constraint (beyond implementing the validation logic), describes how it can be projected on a set of predefined static constraint dimensions. What does that mean? It is a long-winded way of saying that every constraint describes whether:

  • it enforces non-nullability, nullability or does not enforces it.
  • it enforces a length constraint or does not.
  • it enforces a maximum value or does not.

and so on. This will require some work from the presentation framework to embrace and use the Bean Validation API but it will bring a lot of value add to the developers.

The integration with Java Persistence and the way it generates the database schema will be much the same: just replace the words 'form input' with 'column'.

InfoQ: The specification is quite heavily influenced by the Hibernate Validation but the group concept seems to be something of a departure. Could you tell us a bit about where the idea for this came from and how you seeing it being used?

EB: The specification has borrowed a lot from Hibernate Validation, but has grabbed ideas from a lot of different validation frameworks too. That being said, the best way to minimize errors in the spec was to base it on existing working features: as a matter of fact, most features in the spec have been tested either by implementing a proof of concept from the ground up or by forking Hibernate Validator to be sure they fly.

I don't know exactly where and how the group feature was born, so pardon me if I miscredit it. I know Rifle had a similar feature for a long time and I remember Hibernate Validator users asking for this kind of feature. The hard thing about groups and dependencies between constraints in general is that describing them can soon become very, very verbose and complex. The specification tries to achieve a balance between flexibility and simplicity. We already have some interesting discussions started in the feedback forum to try and improve it.

Groups are very important in several cases:

  • defining a subset of constraints to group them by use cases (the user is valid and has provided enough information to buy in one click)
  • validating data as it is provided by the user: not all data is provided at the same time. A given object might be only partially validatable
  • some constraints should be validated after others, and not validated unless the previous validations pass. It might be because they are expensive in time or CPU or because they expect data to be in a "decent" state.

Groups provide a declarative solution for all those use case. We anticipate that Java Persistence, JSF, Web Beans or any application framework will provide a declarative way to request group specific validations.

InfoQ: How are you working with the other expert groups where there is potential overlap? For example in JPA2, Web Beans etc.

EB: Strictly speaking, there is no overlap between JSR 303 and the specifications you mention but there are definitely integration opportunities. While the integration work has not formally started, various members of the 303 expert group are also members of the JPA 2, JSF 2 and Web Beans expert groups. I am personally part of the JPA 2 expert group and have been thinking about Java Persistence integration for a while. With the early draft out, the other expert groups can comment and provide feedback to make this integration a reality.

InfoQ: How soon will a prototype implementation be available?

EB: Actually the community beat us. You can find some implementations out there already. I am aware of
While not compliant (especially API wise), Hibernate Validator implemeants most of the concepts behind the specification and explores the front to back integration model we just discussed:

  • it integrates with Hibernate Core to synchronize the database schema
  • it integrates with JBoss Seam and JSF through the tag. This tag triggers a call to Hibernate Validator on the form properties before passing them to the rest of the application flow
  • some UI widgets reuse Hibernate Validator constraints and apply them on the client side through JavaScript calls

InfoQ: What are you looking for from the Java community?

EB: We are very eager to get feedback on the specification:

  • how well does it fit application developer needs (ease of use, use cases)
  • how well does it fit framework developer needs (integration points, reusability)
  • how can it be improved

We have moved away from an email based feedback system and opened a public forum where people can interact, ask questions, propose alternative solutions. This is the perfect time to change and enhance the specification. Feedback so far has been very good and interesting so keep going :)

Rate this Article