I'm using Hibernate Validator 4.2.0.Final and I'm looking for the simplest way to include class field name in my error message.
What I found is the following thread Using a custom ResourceBundle with Hibernate Validator. According to this I should create my custom annotation for each constraint annotation adding one property to each one.
Is there a cleaner way to achieve this?
The following code:
@Size(max = 5) private String myField;
produces default error: size must be between 0 and 5.
I would like it to be: myField size must be between 0 and 5.
You can get the name of the field with the getPropertyPath()
method from the ConstraintViolation
class.
A good default error message can be:
violation.getPropertyPath() + " " + violation.getMessage();
Which will give you "foo may not be null", or "foo.bar may not be null" in the case of nested objects.
If your messages are in .properties
file then there is no interpolation variable for accessing property name but one way you can achieve that is
//in ValidationMessages.properties app.validation.size.msg=size must be between {min} and {max} @Size(min=10, max=15, message = "myField {app.validation.size.msg}) private String myField;
OR
//in ValidationMessages.properties app.validation.size.msg=size must be between {min} and {max} but provided ${validatedValue} @Size(min=10, max=15, message = "myField {app.validation.size.msg}) private String myField;
Reference: message interpolation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With