【问题标题】:How do I display the field name description in the constraint violation message of a custom constraint annotation?如何在自定义约束注释的约束违规消息中显示字段名称描述?
【发布时间】:2015-04-23 15:05:20
【问题描述】:

如何在Bean Validation 1.1 (JSR-349)自定义约束注解的约束违规消息中显示字段名描述?

例如,给定以下自定义约束注释@Required、资源包ValidationMessages.properties 和类Person,我该如何编写约束违规消息“First Name is required.”对于必填字段firstName 和“姓氏是必填项。”对于必填字段lastName?

@Documented
@Constraint(validatedBy = {})
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@NotEmpty
@ReportAsSingleViolation
public @interface Required {
    public abstract Class<?>[] groups() default {};
    public abstract String message() default "{Required.message}";
    public abstract Class<? extends Payload>[] payload() default {};
}

在资源包中,ValidationMessages.properties:

Required.message=is required.

班级Person:

public class Person {
    @Required
    private String firstName;

    @Required
    private String lastName;
}

【问题讨论】:

    标签: java bean-validation jsr349


    【解决方案1】:

    ConstraintViolation constraintViolation .. ((PathImpl)constraintViolation.getPropertyPath()).getLeafNode().getName();

    【讨论】:

    【解决方案2】:

    没有可用于获取当前属性名称的 API。如果有,您仍然需要进行一些字符串操作,以从属性名称“firstName”获取显示名称“First Name”。

    也就是说,我可以看到在传递给ConstraintValidator#isValidConstraintValidatorContext 中公开当前Path 的好处。这是按规范不可能的 atm,但它可以作为提供者特定的功能来实现。您可以为 Hibernate Validator here 创建问题请求。

    关于您的问题,最好的解决方案是添加一个 'labelattribute to@Required`:

    public class Person {
        @Required(label="First Name"
        private String firstName;
    
        @Required(label="Last Name"
        private String lastName;
    }
    

    然后你可以像这样在消息包中插入标签:

    Required.message={label} is required.
    

    约束看起来像这样

    @Documented
    @Constraint(validatedBy = {})
    @Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
    @Retention(RetentionPolicy.RUNTIME)
    @NotEmpty
    @ReportAsSingleViolation
    public @interface Required {
        public abstract String label();
        public abstract Class<?>[] groups() default {};
        public abstract String message() default "{Required.message}";
        public abstract Class<? extends Payload>[] payload() default {};
    }
    

    注意,你可以添加你喜欢的参数(前提是Java支持的参数类型)。

    【讨论】:

    • 如何将label 添加到@Replace
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2020-03-28
    • 1970-01-01
    • 2018-07-02
    相关资源
    最近更新 更多