Class level bean validation with f:valdiateWholeBean
JSF provides a f:validateBean which bridges Bean Validation to JSF, why we need another f:validateWholeBean?
This is explained in details in the VDL docs of f:validateWholeBean.
Support multi-field validation by enabling class-level bean validation on CDI based backing beans. This feature causes a temporary copy of the bean referenced by the value attribute, for the sole purpose of populating the bean with field values already validated by and then performing class-level validation on the copy. Regardless of the result of the class-level validation, the copy is discarded.
in another word, it provides the capability of cross fields validation.
A good example is password matching check in a signup page, we have to make sure the values in password field and password confirm field are equivalent.
Create a bean validation annotation @Password.
@Constraint(validatedBy=PasswordValidator.class)
@Target(TYPE)
@Retention(RUNTIME)
@interface Password {
String message() default "Password fields must match";
Class[] groups() default {};
Class[] payload() default {};
}Constraint declares which validator will handle this annotation, here it is PasswordValidator.
public class PasswordValidator implements ConstraintValidator<Password, PasswordHolder> {
@Override
public void initialize(Password constraintAnnotation) { }
@Override
public boolean isValid(PasswordHolder value, ConstraintValidatorContext context) {
boolean result;
result = value.getPassword1().equals(value.getPassword2());
return result;
}
}ConstraintValidator accept two parameters, the validator annotation, and the type(PasswordHolder) will be applied.
PasswordHolder is an interface which holds the values of two password fields.
Create a backing bean to put all together.
We apply Password validation on the backingBean, it is a class level validation.
Create a simple facelets template.
f:validateWholeBean accept a value attribute to set the backing bean.
NOTE, we use a PasswordValidationGroup group to differentiate varied validations.
PasswordValidationGroup is just an interface.
Run the project on Glassfish v5, open your browser and navigate to http://localhost:8080/jsf-validwholebean/.
Try to input passwords, if its length is less than 8, submit form, it will display erros like.

If the length is valid, and the two password are not matched, it will trigger the @Password validator.

Grab the source codes from my GitHub account, and have a try.
Last updated
Was this helpful?