0

I'm using hibernate-validator 5.3.0.

The following is my function with @NotNull constraint, where I'm making validation on method parameters.

public void test(@NotNull String firstName, @NotNull String lastName) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 
    Validator validator = factory.getValidator();
    ....
}

After reading this question I found that it's possible to put custom error message in ValidationMessages.properties file with this following format:

[ConstraintName].[ClassName].[FieldName]=[Message] 

for example

NotNull.TestClass.name=My Custom Message

But this works when you're trying to validate some class fields.

So is it possible to use this or some other format and create custom error messages for method arguments?

Thanks in advance.

Community
  • 1
  • 1

1 Answers1

0

Have you looked at message annotation parameter ? You can provide your own custom messages if you want using it for example like this:

public void test(@NotNull(message = "My custom message for first name") String firstName, @NotNull String lastName) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 
    Validator validator = factory.getValidator();
    ....
}

or if you need to reuse the same message a lot of times you can add it to ValidationMessages.properties as you said in your question and later in the code do something like this:

public void test(@NotNull(message = "{my.custom.message.key}") String firstName, @NotNull String lastName) {

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); 
    Validator validator = factory.getValidator();
    ....
}

And in your ValidationMessages.properties you will have:

my.custom.message.key=My custom message goes here

You can find all you need in here - spec

mark_o
  • 2,052
  • 1
  • 12
  • 18