Juan Camacho
Juan Camacho

Reputation: 3

How to add a custom MessageValidationInterpolator with custom files?

Im trying to add a custom validation message each time a Jakarta constraint is not valid. Since the client is requiring this message to be in different languages its crucial to determine the language before returning a message. Currently I have a class that has this information (The language the message is needed).

For that there are files with the messages in a key-pair manner. validation.error.idNullError=The Id cant be null The files names are messages (For english) messages.pt (For Portuguese) etc.

Thinking about a solution, I came across the documentation of Message interpolation.

Since im using validation tags for my validations. In a class like this:

foo class{
  @NotNull(message = "The id cant be null")
  private Integer Id;
}

Declaring a validator like this:

public static final Validator VALIDATOR = Validation.byProvider(HibernateValidator.class)
                                                        .configure()
                                                        .failFast(true)
                                                        .buildValidatorFactory()
                                                        .getValidator();

And validating like this:

ValidationResult.of(VALIDATOR.validate(fooClassInstance))

I encountered two issues:

  1. I couldn't find any documentation regarding on how to add these files (Message files with different languages).
  2. How to add the message to the tag since I want it to look something like this:
@NotNull(message = "{validation.error.idNullError}")

Keep in mind I cant rename the files since they are used in some other parts of the project and documentation only mentions *.properties files

I tried to add a message interpolator but couldn't find any documentation that could satisfy the needs.

Is there a way to use it like im trying to use it?

PDTA: I know that I can add the MessageInterpolator to the validator and pass the language in the constructor, but I don't know how to reach the files to make a bundle for the intepolator.

Upvotes: 0

Views: 18

Answers (0)

Related Questions