如何组合验证两个或多个字段? [英] How can I validate two or more fields in combination?

查看:22
本文介绍了如何组合验证两个或多个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JPA 2.0/Hibernate 验证来验证我的模型.我现在有一种情况,必须验证两个字段的组合:

I'm using JPA 2.0/Hibernate validation to validate my models. I now have a situation where the combination of two fields has to be validated:

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

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

The model is invalid if both getValue1() and getValue2() are null and valid otherwise.

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

How can I perform this kind of validation with JPA 2.0/Hibernate? With a simple @NotNull annotation both getters must be non-null to pass validation.

推荐答案

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

For multiple properties validation, you should use class-level constraints. From Bean Validation Sneak Peek part II: custom constraints:

你们中的一些人表达了担忧关于申请的能力约束跨越多个属性,或表达约束这取决于几个属性.经典的例子是地址验证.地址错综复杂规则:

Class-level constraints

Some of you have expressed concerns about the ability to apply a constraint spanning multiple properties, or to express constraint which depend on several properties. The classical example is address validation. Addresses have intricate rules:

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

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

The solution offered by the Bean Validation specification is two-fold:

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

类级别的限制是常规的约束(注释/实施二人组),适用于类而不是属性.说过不同的是,类级别的约束接收对象实例(而不是isValid 中的属性值).

Class level constraints are regular constraints (annotation / implementation duo) which apply on a class rather than a property. Said differently, class-level constraints receive the object instance (rather than the property value) in 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.经过访问对象实例、类等级限制有很多灵活性,可以验证多个相关属性.注意排序被排除在等式之外在这里,我们将在下一篇.

The advanced address validation rules have been left out of the address object and implemented by MultiCountryAddressValidator. By accessing the object instance, class level constraints have a lot of flexibility and can validate multiple correlated properties. Note that ordering is left out of the equation here, we will come back to it in the next post.

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

The expert group has discussed various multiple properties support approaches: we think the class level constraint approach provides both enough simplicity and flexibility compared to other property level approaches involving dependencies. Your feedback is welcome.

这篇关于如何组合验证两个或多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆