Tuesday, June 1, 2010

multi-field form validation with jsr 303

there is a new extval add-on (new location). this first draft of the add-on allows so called multi-field (or cross-field) validation based on jsr 303.

within the page you just use normal input components - e.g.:



furthermore, you annotate e.g. your page bean with @FormValidator. the annotation also allows to specify a specific view-id, conditions as well as validation groups. to implement a more fine-grained multi-validation it's possible to provide multiple form-bean classes. to implement more complex combinations it's possible to use @FormValidator.List(...). (as alternative you can also us the provided java api to map your bean(s) to a form-validator. so if you don't like to use the annotation you can provide a separated mapping.)

usage of @FormValidator:



in the page you see the id's of the different components. we have to use these id's as field-names (or setter-methods) in the form-validator.

the following figure shows a possible form-validator for this example:



as soon as the form-validator-bean is annotated with @Form, the validator is called by the bean-validation engine. so the violation message gets processed by the bean-validation engine and the final message is added as global faces-message.

(if you would like to use the current ConstraintValidatorContext of bean-validation, you can directly implement the FormBean interface instead of extending ViolationMessageAwareFormBean.)

if you use e.g. input components within a data-table, you can use 'add'-methods instead of the setter-method. in the form-validator you can use a data-structure like a list per column. as soon as the validation process starts (at the end of the validation phase) the form-validator contains all values (in case of input components in tables the validator is aware of all table values). so it's possible to implement any multi-field validation you can imagine (in case of input components in tables also validations per row as well as across rows).

additional features:
it's possible to map the form-bean-class to specific view-id's, to provide conditions as well as validation groups.