是否有一些方法(除了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;
}
}
有什么想法吗?
答案 0 :(得分:0)
您可以针对此类情况使用群组。
因此,请删除checkBar
字段,然后只指定CheckBarGroup
。
像
validator.validate(testForm)
或validator.validate(testForm, CheckBarGroup.class, Default.class)