调用类级别 JSR-303 约束的最佳方法是什么,这些约束从 JSF 进行跨字段验证,并将生成的消息转换为 FacesMessage,并根据 ConstraintViolation 中的 PropertyPath 绑定(bind)到特定的 JSF 组件?
rich:graphValidator很接近,但它没有使用 PropertyPath。也许 MyFaces extval 可以让我接近,但在 bean 验证时似乎有一个额外的框架层,所以我避免了它。
这是一个简单的例子:
public enum Type {
ROAD, RACE;
}
public class Driver {
private String name;
private Type licenseType;
...
}
@CarConstraint
public class Car {
@Valid
private Driver driver;
private Type carType;
private String make;
private String model;
...
}
public class CarConstraintValidator implements ConstraintValidator<CarConstraint, Car> {
@Override
public void initialize(CarConstraint constraintAnnotation) {}
@Override
public boolean isValid(Car value, ConstraintValidatorContext context) {
if (value == null) { return true; }
if (Type.RACE.equals(value.getCarType())
&& !Type.RACE.equals(value.getDriver().getLicenseType())) {
context.buildConstraintViolationWithTemplate("Driver of this car must have a racing license")
.addNode("driver")
.addNode("licenseType")
.addConstraintViolation();
return false;
}
return true;
}
}
想象一个表单,其中输入了有关汽车和司机的信息。如果 Driver 的执照类型为 ROAD 而 Car 的汽车类型为 RACE,那么理想的情况是看到生成的验证消息被转换为 FacesMessage,它连接到执照类型的输入,因为该消息已添加使用 Bean Validation 的流畅 API 到该节点。
最佳答案
我们的团队遇到了同样的问题。你可以看看OmniFaces .我使用来自 validator 的代码作为蓝图来构建使用反射调用类级别 validator 的原型(prototype)。
关于java - 使用 JSR 303 在 JSF 中使用内联消息传递进行跨字段验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5639088/