允许覆盖/设置子对象的约束验证以进行Hibernate验证

问题描述

我有以下课程:

class ContactInformation {
   String phone;
   String email;
}

在以下类中使用:

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

问题是Person的任何实例都必须具有电子邮件,但这是Station的可选信息。我是否可以在所有者级别定义此方法以避免重复类ContactInformation

解决方法

您可以添加 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;
    }

Reference

Gist

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...