Java Bean验证(JSR303)约束涉及多个Bean属性之间的关系 [英] Java Bean Validation (JSR303) constraints involving relationship between several bean properties

查看:369
本文介绍了Java Bean验证(JSR303)约束涉及多个Bean属性之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下简单的Java bean:

Say I have the following simple java bean:

class MyBean {
   private Date startDate;
   private Date endDate;
   //setter, getters etc...
}

JSR 303中是否存在一种机制来创建自定义验证程序,以验证startDate必须在endDate之前的约束?

Is there a mechanism in JSR 303 to create a custom validator that validates the constraint that startDate must be before endDate?

在我看来,这是一个常见的用例,但是我找不到这种多属性关系约束的任何示例.

It seems to me to be a common use case, yet I cannot find any examples of this kind of multiple property relationsship constraint.

推荐答案

我可以考虑尝试一些方法.

I can think of a few things to try.

您可以创建一个Constraint,其类型本身的目标带有适当的验证器:

You could create a Constraint with a target of the type itself with an appropriate validator:

@ValidateDateRange(start="startDate", end="endDate")
public class MyBean {

您可以将日期范围封装为一种类型,并验证以下内容:

You could encapsulate a date range in a type and validate that:

public class DateRange {    
  private long start;
  private long end;

  public void setStart(Date start) {
    this.start = start.getTime();
  }

  // etc.

您可以添加执行检查的简单属性:

You could add a simple property that performs the check:

public class MyBean {
  private Date startDate;
  private Date endDate;

  @AssertTrue public boolean isValidRange() {
    // TODO: null checks
    return endDate.compareTo(startDate) >= 0;
  }

这篇关于Java Bean验证(JSR303)约束涉及多个Bean属性之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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