【问题标题】:Allow to override/set constraints validation for a child object for Hibernate validation允许为 Hibernate 验证的子对象覆盖/设置约束验证
【发布时间】:2020-09-04 13:43:43
【问题描述】:

我有以下课程:

class ContactInformation {
   String phone;
   String email;
}

在以下类中使用:

class Person {
   @Valid
   ContactInformation contactInformation;
}
class Station {
   @Valid
   ContactInformation contactInformation;
}

问题是任何 Person 实例都必须有一个电子邮件,但它是 Station 的可选信息。我有办法在所有者级别定义它以避免重复类ContactInformation 吗?

【问题讨论】:

    标签: java bean-validation hibernate-validator


    【解决方案1】:

    您可以添加Type 级别验证器,而不是field 级别验证器。 步骤:

    • 定义类型级别注释
    • 为新注释编写验证器
    • 使用新注释介绍您的类型

    定义:

        @Constraint(validatedBy = {PersonClassOptionalEmailValidator.class})
        @Target({ElementType.TYPE})
        @Retention(RetentionPolicy.RUNTIME)
        public @interface PersonalEmailValid {
            String message() default "Invalid Email address";
    
            Class<?>[] groups() default {};
    
            Class<? extends Payload>[] payload() default {};
    
        }
    

    编写自定义验证器:

        public static class PersonClassOptionalEmailValidator implements ConstraintValidator<PersonalEmailValid, Person> {
            // Test Email validator, you should check prope regex for production
            public static final String EMAIL_REGEX = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
            private final Pattern pattern;
    
    
            public PersonClassOptionalEmailValidator() {
                pattern = Pattern.compile(EMAIL_REGEX);
            }
    
            @Override
            public boolean isValid(Person person, ConstraintValidatorContext constraintValidatorContext) {
                if (person.contactInformation != null) {
                    return pattern.matcher(person.contactInformation.email).matches();
                }
                return false;
            }
        }
    

    给类引入新的注解

        @Getter
        @Setter
        @NoArgsConstructor
        @PersonalEmailValid
        static class Person {
            @Valid
            ContactInformation contactInformation;
        }
    

    Reference

    Gist

    【讨论】:

    • 感谢您的回复。我真的很想避免为此创建自定义验证器。
    猜你喜欢
    • 2012-11-13
    • 2017-04-14
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多