Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate validation-specific parameters in bean validation message

I have a custom bean validator which checks if a given field on an entity is unique for some conditions. If the validation fails, the message should include a field (e.g. the ID) of the already existing entity. So for example the message should be:

"Product 42 already has such a value defined, choose a unique value."

Is this possible using bean validation?

AFAICS, the message format may include parameters, such as:

"Length must be between {min} and {max}."

But this can only reference the "static" attributes of the validation annotation, in this case:

@Size(min=1, max=16)
private String name;

In my case, the value is only known within isValid of my custom validator.

like image 956
robinst Avatar asked Jan 04 '11 17:01

robinst


1 Answers

You are right!, And for what you want!, you can build constraint violation message inside the isValid() method. For this the constraints Annotation should be specific for particular class on which it has been applied and it should be a class level validation constraints. Inside isValid before returning false on failure of validation you can create message consisting value of class instance. For example:

@check class Test{ int id; @validations...on fields}.

public boolean isValid(Test value, ConstraintValidatorContext context) 
{
// your check logic
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("It should be different for(custom message) .."+ value.id).addConstraintViolation();
return false; // based on constraint filure.

}

But i think you want to do this with Field level annotations! I don't have idea about that looking forward to your results.

like image 179
Kumar Avatar answered Oct 21 '22 12:10

Kumar