允许覆盖/设置hibernate验证的子对象的约束验证

apeeds0o  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(342)

我有以下课程:

class ContactInformation {
   String phone;
   String email;
}

用于以下类别:

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

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

r6l8ljro

r6l8ljro1#

而不是 field 你可以添加 Type 等级验证器。步骤:
定义类型级别注解
为新注解编写验证程序
用新注解介绍你的类型
定义:

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

参考
主旨

相关问题