I am working in a project using JPA, and Bean Validation. I want to show friendly messages to the user about the validations that failed, and I need to show these messages in different languages based on the Locale of the users.
I am using standard annotations like @NotNull
, @Size
, as well as some custom class level validations.
I am using the following code to validate the entities before persist them:
Validator validator = validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Company>> constraintViolations = validator.validate(company);
if (constraintViolations.size() > 0) {
Set<String> violationMessages = new HashSet<String>();
for (ConstraintViolation<Company> constraintViolation : constraintViolations) {
violationMessages.add(constraintViolation.getPropertyPath() + ": " + constraintViolation.getMessage());
}
}
If validation failed I can see the messages and the fields that failed validation, but I don't know how to convert these validation messages to friendly ones and in different languages (based on the Locale
of the users).
I have the following questions:
- What is the proper way to achieve this?
- I know that JPA checks automatically the entities against validations before persist. If I execute the validation manually (with the above code) am I running the validation process twice?
- If I am using JSF which also executes validations before update the model, I am running the validation process three times (1. JSF, 2. the above code and 3. Wildfly/JPA before persist/merge)?
- If the above code runs in an EJB, how can I pass the validation errors to the presentation layer (JSF for example)?
- Do I need to return a list of ConstraintViolations to the presentation layer? - Do I need to create an exception for each validation?
Thank you