如何组合验证两个或多个字段?

2022-08-31 09:02:17

我正在使用 JPA 2.0/Hibernate 验证来验证我的模型。我现在遇到必须验证两个字段的组合的情况:

public class MyModel {
    public Integer getValue1() {
        //...
    }
    public String getValue2() {
        //...
    }
}

如果两者兼而有之,则该模型无效getValue1()getValue2()null

如何使用 JPA 2.0/休眠执行此类验证?对于简单的注释,两个 getter 都必须为非 null 才能通过验证。@NotNull


答案 1

对于多属性验证,应使用类级约束。来自 Bean 验证先睹为快第二部分:自定义约束

类级约束

你们中的一些人对应用跨越多个属性的约束或表达依赖于多个属性的约束的能力表示担忧。经典示例是地址验证。地址有错综复杂的规则:

  • 街道名称有点标准,必须有长度限制
  • 邮政编码结构完全取决于国家
  • 城市通常可以与邮政编码相关联,并且可以进行一些错误检查(前提是可以访问验证服务)
  • 由于这些相互依赖关系,一个简单的属性级约束确实符合要求

Bean 验证规范提供的解决方案有两个方面:

  • 它提供了通过使用组和组序列强制在另一组约束之前应用一组约束的能力。这个主题将在下一篇博客文章中介绍
  • 它允许定义类级约束

类级约束是常规约束(注释/实现二重奏),适用于类而不是属性。换句话说,类级约束接收 的对象实例(而不是属性值)。isValid

@AddressAnnotation 
public class Address {
    @NotNull @Max(50) private String street1;
    @Max(50) private String street2;
    @Max(10) @NotNull private String zipCode;
    @Max(20) @NotNull String city;
    @NotNull private Country country;
    
    ...
}

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

public class MultiCountryAddressValidator implements ConstraintValidator<AddressAnnotation, Address> {
    public void initialize(AddressAnnotation constraintAnnotation) {
    // initialize the zipcode/city/country correlation service
    }

    /**
     * Validate zipcode and city depending on the country
     */
    public boolean isValid(Address object, ConstraintValidatorContext context) {
        if (!(object instanceof Address)) {
            throw new IllegalArgumentException("@AddressAnnotation only applies to Address objects");
        }
        Address address = (Address) object;
        Country country = address.getCountry();
        if (country.getISO2() == "FR") {
            // check address.getZipCode() structure for France (5 numbers)
            // check zipcode and city correlation (calling an external service?)
            return isValid;
        } else if (country.getISO2() == "GR") {
            // check address.getZipCode() structure for Greece
            // no zipcode / city correlation available at the moment
            return isValid;
        }
        // ...
    }
}

高级地址验证规则已从地址对象中省略,并由 实现。通过访问对象实例,类级约束具有很大的灵活性,可以验证多个相关属性。请注意,排序在这里被排除在外,我们将在下一篇文章中回到它。MultiCountryAddressValidator

专家组讨论了各种多属性支持方法:我们认为,与其他涉及依赖关系的属性级方法相比,类级约束方法提供了足够的简单性和灵活性。欢迎您提供反馈。


答案 2

为了正确使用Bean Validation,Pascal Thivent的答案中提供的示例可以重写如下:

@ValidAddress
public class Address {

    @NotNull
    @Size(max = 50)
    private String street1;

    @Size(max = 50)
    private String street2;

    @NotNull
    @Size(max = 10)
    private String zipCode;

    @NotNull
    @Size(max = 20)
    private String city;

    @Valid
    @NotNull
    private Country country;

    // Getters and setters
}
public class Country {

    @NotNull
    @Size(min = 2, max = 2)
    private String iso2;

    // Getters and setters
}
@Documented
@Target(TYPE)
@Retention(RUNTIME)
@Constraint(validatedBy = { MultiCountryAddressValidator.class })
public @interface ValidAddress {

    String message() default "{com.example.validation.ValidAddress.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
public class MultiCountryAddressValidator 
       implements ConstraintValidator<ValidAddress, Address> {

    public void initialize(ValidAddress constraintAnnotation) {

    }

    @Override
    public boolean isValid(Address address, 
                           ConstraintValidatorContext constraintValidatorContext) {

        Country country = address.getCountry();
        if (country == null || country.getIso2() == null || address.getZipCode() == null) {
            return true;
        }

        switch (country.getIso2()) {
            case "FR":
                return // Check if address.getZipCode() is valid for France
            case "GR":
                return // Check if address.getZipCode() is valid for Greece
            default:
                return true;
        }
    }
}

推荐