Help

The public draft of Bean Validation is finally out and available here on the JCP website. We have made a lot of improvements and took a lot of feedback from you since the last draft:

  • interface-based groups
  • constraint composition
  • built-in constraints
  • multiple reports per constraint violation
  • bootstrap API
  • method level validation
  • integration with JPA, JSF and Java EE

Please go check the spec and give us your feedback in our forum. We plan to get a final spec early february, so don't delay :)

Groups

The fundamental notion of group is basically unchanged but it has morphed into a much more type-safe and cleaner beast. Instead of declaring groups as strings, groups are now interfaces. This has several advantages including:

  • easier to find a group usage in IDEs
  • errors due to typos will be visible at compilation time rather than runtime
  • groups can inherit from each other using the natural interface inheritance model. This allows group composition.
  • partial validation based on interfaces hosting constraint definitions
/** 
 * Customer can buy bypassing the harassing checking process 
 * 
 * @author Emmanuel Bernard 
 */ 
public interface BuyInOneClick extends Default, Billable {} 

/** 
 * User representation 
 */ 
public class User { 
    @NotNull private String firstname; 
    @NotNull(groups = Default.class) private String lastname; 
    @NotNull(groups = {Billable.class}) private CreditCard defaultCreditCard; 
}

Set<ConstraintViolation> violations = validator.validate(user, BuyInOneClick.class);

The spec is very readable and has a lot of real-life examples, check section 3.4.

Constraints

Constraints can now declaratively be composed of more primitive constraints. This both helps to reduce code duplication and to allow primitive constraints to be exposed in the metadata and used by tools like JavaScript generators.

@Numerical
@Size(min=5, max=5)
@ConstraintValidator(FrenchZipcodeValidator.class)
@Documented
@Target({ANNOTATION_TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface FrenchZipCode {
    String message() default "Wrong zipcode";
    Class<?>[] groups() default {};
}

I described the idea in more details in this previous blog entry.

Speaking of constraint definition, the specification now comes with a set of built-in constraints: @Null, @NotNull, @AssertTrue, @AssertFalse, @Min, @Max, @Size, @Digits, @Past, @Future. These are the fundamental bricks that can be understood by all tools accessing metadata.

Finally, constraint implementations can now raise more than one violation report per constraint. This is particularly useful when a bean-level constraint is targeting two specific properties.

@CheckAddressConsistency
public class Address {
  private String zipCode;
  private String city;
}

@CheckAddressConsistency probably wants to raise two violation reports, one targeting zipCode and one targeting city. This is also useful to define fine grained error messages depending on the failure. See section 2.4 for more info.

API

The Validator interface can now validate any type of object and is no longer tied to a given JavaBean type.

Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<Address>> addressViolations = validator.validate(address);
Set<ConstraintViolation<User>> userViolations = validator.validate(user);

The specification has a bootstrap API letting you customize various validation components and optionally letting you choose the specific Bean Validation provider you seek. An older version of the bootstrap API is described in this blog entry, the latest version is of course available in the spec section 4.4.

In appendix, you will find a proposal for method level validations: parameter and returned values can be decorated with constraints declarations. This feature has been widely requested, let us know what you think.

Integration

The JPA, JSF and Java EE integration proposals are also available in appendix.

Thanks to everyone for your past feedback and your future one :)

6 comments:
 
07. Jan 2009, 01:31 CET | Link
Daoud AbdelMonem Faleh

Great! I asked about Constraints composition since your first proposal :)

ReplyQuote
 
07. Jan 2009, 02:37 CET | Link
"Tout vient a point a qui sait attendre" meaning roughly All things come in good to those who knows how to wait :)
08. Jan 2009, 17:10 CET | Link

Great news about the parameters validation proposal. Just had a look at it, it looks great. We just finished implementing a very similar solution, so we'll try to refactor our code so that it gets closer to the proposal while waiting for the final spec.

Just one small thing about parameters validation that might be really related to the BeanValidation spec. Example with the following signature:

MyObject myMethod(OneType theType) { ... }

At the moment, by default, it's not possible to display something like Validation error: parameter theType is null although it shouldn't. Because actually the parameter name is not accessible using the reflection API. So, what we currently display is just something like Validation error: parameter n°1 is null although it shouldn't which is less clear that the previous message, you'll agree.

I discovered this project: My Link that lets you workaround this by adding information into the bytecode after compilation, but it's not quite standard. It's said on this page that this information was initially scheduled to be added into JDK7, but finally wouldn't certainly go into because not enough time...

Maybe the priority of being able to access this information at runtime could be now put to a higher priority thanks to the new validation need/usefulness, isn't it?

Anyway, validation is a field that really needed some standardization and good practices. Thanks a lot for all this work.

Cheers

 
03. Feb 2009, 05:19 CET | Link

Emmanuel JSR 303 es una de los mejores esfuerzos que se ha visto en Java en cuanto a validación. Lo que pasa con esta JSR es que se necesita hacer una interfaz para dar la noción de agrupación.

1. Esto tiene el problema de que se usan las interfaces para lo que no fueron diseñadas ósea para ser simples marcadores. 2. Es verboso.

Es preferible tener una solución en Enums

public enum PersonGruop{ ClienteGroup, EmployeeGroup, AdministratorGruop }

Lo único que hay que tener es un campo con el nombre groups y después absorber o procesar las enumeraciones que contenga el campo (field groups dentro de la annotation).

 
21. Jun 2014, 15:50 CET | Link

Technical analysis of Forex charts is done with help of popular technical analysis indicators and drawing tools, which are readily available directly on the forex charts The Forex trading platform is one of the most essential elements Forex traders must take into account, when joining any online Forex trading company. The MetaTrader (MT4) platform would serve the purpose as the traders working area best forex trading platform

 
29. Aug 2014, 07:01 CET | Link
obat kanker otak herbal

I want to appreciate your appropriately written article its useful and your writing style helped me to that without the difficulty. Thanks obat kanker prostat herbal obat kanker hati herbal obat kanker otak herbal

Post Comment