Include field name inside error message using Hibernate Validator

I put every field validation message into the properties file, like this:

field.student.name.size.message = Student name size is not valid.

and in the bean, use it like this:

@Size(max = 5, message = "${field.student.name.size.message}")  
private String myField;

I know it isn't a perfect solution, but I also don't find a better way.


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