将validator.validate中的ConstraintViolation集合与ConstraintValidatorContext合并

时间:2011-10-17 14:50:35

标签: java spring-mvc bean-validation hibernate-validator

是否有一些方法(除了foreach,但良好的foreach就足够了),从validator.valid返回来自ConstraintValidator的消息?

简单的例子(是的,我正在尝试进行条件验证)

@TestFormConstraint
public class TestForm {

    @NotEmpty
    String foo;

    boolean checkBar = false;

    @NotEmpty(groups=CheckBarGroup.class)
    String bar;

    //getters & setters ...
}
public class TestFormValidator 
        implements ConstraintValidator<TestFormConstraint, TestForm> {

    @Autowired
    private Validator validator;

    @Override
    public void initialize(ValidTestForm constraintAnnotation) {}

    @Override
    public boolean isValid(TestForm form, ConstraintValidatorContext context) {
        if(form.isCheckBar()){
            Set<ConstraintViolation<TestForm>> con = 
                    validator.validate(form, CheckBarGroup.class);
            if(!con.isEmpty()){
                //ok, so what to do here? iterate over con and for each msg 
                //call context.buildConstraintViolationWithTemplate ?
                return false;
            }
        }
        return true;
    }

}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以针对此类情况使用群组。 因此,请删除checkBar字段,然后只指定CheckBarGroup

validator.validate(testForm)validator.validate(testForm, CheckBarGroup.class, Default.class)