0

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

Jucaalpa
  • 310
  • 1
  • 4
  • 15
  • Your question suggests that you want to validate a bean whose properties are not (directly) set via JSF input fields, is this true? If so, why exactly don't you just bind those bean properties to JSF input fields and hereby utilize JSF built-in Bean Validation support? – BalusC Jun 08 '19 at 20:01
  • Actually, I am trying to make a cross field validation (which it's supported in JSF 2.3 throught class level validation) but I want that cross field validations be in the business logic and not in the presentation layer. I also want that the validations be executed just once because they do some queries to the database. The problem is that I don`t know how to convert the ConstraintValidation list in friendly messages to the user and pass them to the presentation layer. – Jucaalpa Jun 08 '19 at 20:12

0 Answers0