Skip to content
Advertisement

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.

Advertisement

Answer

For all those who are looking for a way to access class inside your validator. Putting hibernate annotating on a class level instead of variable level gives you access to a class object (assuming that you have defined a custom validator).

public class myCustomValidator implements ContraintValidator <MyAnnotation, MyAnnotatedClass> {

    public void initialize (...){ ... };

    public boolean isValid (MyAnnotatedClass myAnnotatedClass) {

        // access to elements of your myAnnotatedClass

    }
} 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement