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

新手上路,请多包涵

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

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

如果 getValue1()getValue2() 都是 null 则模型 _无效_,否则有效。

我如何使用 JPA 2.0/Hibernate 执行这种验证?使用简单的 @NotNull 注释,两个 getter 都必须为非空才能通过验证。

原文由 Daniel Rikowski 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 764
2 个回答

对于多属性验证,您应该使用类级约束。来自 Bean Validation Sneak Peek 第二部分:自定义约束

类级约束

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

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

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

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

类级约束是应用于类而不是属性的常规约束(注释/实现二重奏)。换句话说,类级约束在 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 实现。通过访问对象实例,类级别的约束具有很大的灵活性,并且可以验证多个相关属性。请注意,这里不考虑排序,我们将在下一篇文章中再次讨论。

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

原文由 Pascal Thivent 发布,翻译遵循 CC BY-SA 4.0 许可协议

为了正确使用 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;
        }
    }
}

原文由 cassiomolin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题