我正在为指定错误消息的类编写验证。一个成员是具有有效性的另一个类的对象的List<>。我想验证该列表中的每个对象,以便oval返回的违规列表具有所需的信息。
示例:
class A{
@AssertValid
List<B> items;
}
class B{
@NotNull(message="ID can't be null")
Integer id;
}现在,让我们假设我的主要内容是:
A obj = new A();
List<B> items = new ArrayList<>();
items.add(new B());
a.setItems(items);
List<ConstraintViolation> violations = validator.validate(obj);
if(violations.size()>0) {
System.out.println(violations.get(0).getMessage());
}它将打印的是"enet.sf.oval.constraint.AssertValid: com.A is invalid",而不是"ID Can't be null“。
是否有一个选项可以指定为OVal来验证每个项目,而不是整个列表?
谢谢
发布于 2016-03-07 10:39:40
您可以通过使用自己的MessageFormatter来做到这一点:
public class CustomMessageValueFormatter implements MessageValueFormatter {
public static final CustomMessageValueFormatter INSTANCE = new CustomMessageValueFormatter();
@Override
public String format(Object value) {
Validator validator = new Validator();
List<ConstraintViolation> constraintViolations = validator.validate(value);
List<String> errorMessages = new ArrayList<>();
constraintViolations.forEach(v -> errorMessages.add(v.getMessage()));
return errorMessages.isEmpty() ? value.toString() : errorMessages.toString();
}
}
class A{
@AssertValid(message = "{invalidValue}")
List<B> items;
}
class B{
@NotNull(message="ID can't be null")
Integer id;
}在验证之前,请将自定义MessageFormatter设置为:
Validator.setMessageValueFormatter(CustomMessageValueFormatter.INSTANCE);发布于 2016-06-24 23:28:41
默认情况下,OVal会验证列表中的项。违规详细信息可通过ConstraintsViolatedException#getConstraintViolations()获得。
生成的ConstraintViolation对象有一个getCauses()方法,它允许您检索关于级联违规(即违反子对象)的详细信息。
https://stackoverflow.com/questions/35316989
复制相似问题