When validating collections, is there a way to know the position a bean being validated from within custom constraint validator?

huangapple 未分类评论47阅读模式
英文:

When validating collections, is there a way to know the position a bean being validated from within custom constraint validator?

问题

让我们看一下下面的用例。

我有一个带有其他一些bean的集合的bean作为其属性之一:

public class MyBean {
    ...
    @Valid
    private NestedBean[] nestedBeans;
    ...
}

嵌套的bean具有如下的自定义类级约束:

@SomeConstraint
public class NestedBean {
    ...
}

而且我们有一个验证器来验证这个自定义约束:

public SomeConstraintValidator implements ConstraintValidator<SomeConstraint, NestedBean> {
    ...
    public boolean isValid(NestedBean bean, ConstraintValidatorContext context) {
        ...
    }
}

有没有办法知道当前正在进行验证的 "bean" 对象的位置,以便我们可以显示错误消息,例如:

"第三个嵌套bean无效..."

或者有其他的方法可以实现这个吗?

Hibernate的ConstraintValidationContext实现保存了这些详细信息的属性路径,但不是公共API。

英文:

Lets take this below use case.

I have bean with collection of some other bean as one of its properties:

public class MyBean {
    ...
    @Valid
    private NestedBean[] nestedBeans;
    ...
}

The nested bean has a custom class level constraint like this:

@SomeConstraint
public class NestedBean {
    ...
}

And we have a validator that validates this custom constraint:

public SomeConstraintValidator implements ConstraintValidator&lt;SomeConstraint, NestedBean&gt; {
    ...
    public boolean isValid(NestedBean bean, ConstraintValidatorContext context) {
        ...
    }
}

Is there a way to know the position of the current "bean" object that is getting validated, so that we can show error messages like:

"The third nested bean is invalid...."

Or is there any other way to achieve this?

The Hibernate's ConstraintValidationContext implementation hold property path with these details, but is not a public API.

huangapple
  • 本文由 发表于 2020年5月29日 22:17:35
  • 转载请务必保留本文链接:https://java.coder-hub.com/62088023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定