Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include field name inside error message using Hibernate Validator

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.

like image 737
BartoszMiller Avatar asked Jul 11 '12 11:07

BartoszMiller


2 Answers

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.

like image 123
brunov Avatar answered Oct 14 '22 12:10

brunov


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

like image 39
user3640709 Avatar answered Oct 14 '22 10:10

user3640709