Bean validation message with dynamic parameters

I started using bean validation, and I'm trying to build constraints My constraint is to verify CPF (personal file in Brazil) My constraint is valid, but I need the message to contain dynamic parameters

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 context Buildconstraintviolationwithtemplate customize 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 do I pass a validation value (CPF) through a parameter when creating a message?

Solution

When using hibernate validator > = 4.2, you can validate the value through ${validatedvalue} reference in the message (in bean validation 1.1 standardized in the specification):

cpf.validation.message=Cpf ${validatedValue} é inválido

By the way Hibernate validator has attached @ CPF constraint. You can find more information in reference guide I'm glad to hear that it works for you

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>