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.
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.
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