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

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

问题描述

我正在使用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(),则模型无效 code>和 getValue2() null ,否则有效。

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

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

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 Validation Sneak Peek第二部分:自定义约束

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:


  • 街道名称有些标准,必须有长度限制

  • 邮政编码结构完全取决于国家/地区

  • 城市通常可以与邮政编码相关联,一些错误检查可以
    完成(前提是确认
    服务是可访问的)

  • 因为这些相互依赖性,一个简单的属性级别约束会使
    适合账单

  • a street name is somewhat standard and must certainly have a length limit
  • the zip code structure entirely depends on the country
  • the city can often be correlated to a zipcode and some error checking can be done (provided that a validation service is accessible)
  • because of these interdependencies a simple property level constraint does to fit the bill

Bean
验证规范提供的解决方案是双重的:

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


  • it通过
    使用组和组序列,可以强制在
    其他约束集之前应用一组约束。
    此主题将在
    下一篇博文中介绍

  • 它允许定义类级约束

类级约束是常规的
约束(注释/
实现二重奏),它适用于
类而不是属性。换句话说
不同,类级约束
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.

@Address 
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 Address {
    String message() default "{error.address}";
    String[] groups() default {};
}

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

    /**
     * Validate zipcode and city depending on the country
     */
    public boolean isValid(Object object) {
        if (!(object instanceof Address)) {
            throw new IllegalArgumentException("@Address only applies to Address");
        }
        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.

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

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天全站免登陆