JSR-303如何有时会忽略对Bean中特定字段的验证 [英] JSR-303 how to ignore validation on specific fields in a bean some of the time

查看:70
本文介绍了JSR-303如何有时会忽略对Bean中特定字段的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在验证一个大bean.它基于动态表单页面.某些正在验证的字段在窗体上不可见,因此为空或为null.但我不希望对不可见字段进行验证.有时它们是可见的,我希望它们得到验证,有时它们不可见,并且我不希望它们得到验证.在提交之前,我首先采用了从序列化表格中删除这些字段的方法.但是它仍然验证缺少的字段,因为它们存在于带有验证标签的Bean中.做我想做的正确方法是什么?

I am validating a large bean. It is based of a dynamic form page. Some fields that are being validated are not visible on the form and hence empty or null. But I don't want the invisible fields to be validated. Sometimes they are visible and I want them to be validated, sometimes they are not visible and I don't want them to be validated. I first took the approach of stripping these fields from the serialized form before submitting. But it still validates the missing fields because they exist in the bean with validation tags. What is the right way to do what I am trying to do?

推荐答案

一种可能的方法是使用验证组.您为不同的组定义了不同的验证规则.之后,您可以仅针对这些组中的一个或一组组调用验证器.

One possible approach is using validation groups. You define different validation rules for different groups. Afterwards you can call the validator just for one of these groups or for a set of groups.

public class TestBean {

    @NotNull(groups= {Group1.class})
    @Size.List({
        @Size(min=1, groups= {Group1.class}),
        @Size(min=0, groups= {Group2.class})
    })
    private String test;
}

public interface Group1 { }
public interface Group2 { }

然后您可以为其中一个或多个组调用验证器

then you can call the validator for one or more of these groups

Validator validator = ....;
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(objectToValidate, Group1.class);

有关验证组的更多信息,请参见

For more information about validating groups see here.

这篇关于JSR-303如何有时会忽略对Bean中特定字段的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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