I am getting started with bean validation, and I'm trying to compose a constraint. My constraint is to validate a CPF(personal document in Brazil). My constraint is working, but I need the message to contain a dynamic parameter.
I'm using ValidationMessages.properties. My code:
@Constraint(validatedBy=CpfValidator.class)
@Size(min=11, max=14)
@Documented
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Cpf {
String message() default "{cpf.validation.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
My ValidationMessages.properties:
cpf.validation.message=Cpf {cpf} é inválido
My Validator: i'm using a context.buildConstraintViolationWithTemplate to customiza my message.
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
String cpf = value;
boolean result = ValidationUtil.validaCpf(cpf);
if (result) {
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("pf.validation.message}")
.addConstraintViolation();
return false;
}
How can I pass the validated value(cpf) by parameter when the message is created?