小编Hen*_*nry的帖子

带有动态参数的Bean验证消息

我开始使用bean验证,我正在尝试构建约束.我的约束是验证CPF(巴西的个人文件).我的约束是有效的,但我需要消息包含动态参数.

我正在使用ValidationMessages.properties.我的代码:

@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 {};

}
Run Code Online (Sandbox Code Playgroud)

我的ValidationMessages.properties:

cpf.validation.message=Cpf {cpf} é inválido
Run Code Online (Sandbox Code Playgroud)

我的验证器:我正在使用context.buildConstraintViolationWithTemplate来自定义我的消息.

@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;

}
Run Code Online (Sandbox Code Playgroud)

创建消息时,如何通过参数传递验证值(cpf)?

validation message java-ee bean-validation

6
推荐指数
3
解决办法
1万
查看次数

标签 统计

bean-validation ×1

java-ee ×1

message ×1

validation ×1