JSR 303中的GroupSequence和有序评估 [英] GroupSequence and ordered evaluation in JSR 303
问题描述
在我们的应用程序中,有这样一种情况:
In our application we have such a case:
- 应按特定顺序评估约束. (价格便宜)
- 每个字段违反一次后,不应评估约束条件.
- 所有字段均应经过验证.
对于前两个,groupsequence非常合适.但是,对于我的第三个要求,我找不到解决方法.
For first two, groupsequence is fitting very good. However for my 3rd requirement I could not find a way to solve.
public class AccountBean {
@CheepValidation
@ExpensiveValidation
@VeryExpensiveValidation
private String name;
@CheepValidation
@ExpensiveValidation
@VeryExpensiveValidation
private String surname
}
例如,
比方说,对于名称字段VeryExpensiveValidationconstraint违反,对于姓氏字段ExpensiveValidation约束违反.
Let's say that, for name field VeryExpensiveValidationconstraint is violated and for surname field ExpensiveValidation constraint is violated.
在这种情况下,我应该显示:
For this case I should display:
对于字段名称:仅VeryExpensiveValidation错误消息 对于字段姓氏:仅ExpensiveValidation错误消息
For field name: Only VeryExpensiveValidation error message For field surname: Only ExpensiveValidation error message
请注意,对于字段姓氏,我们没有评估VeryExpensiveValidation约束.
Note that for field surname we did not evaluate VeryExpensiveValidation constraint.
是否可以使用JSR 303来实现它?
Is there a way to implement it with JSR 303?
谢谢
推荐答案
您可以使用组和@GroupSequence,但这有点笨拙.
You can use groups and @GroupSequence, but it's a bit unwieldy.
public class AccountBean {
@CheapValidation(groups=Name1.class)
@ExpensiveValidation(groups=Name2.class)
@VeryExpensiveValidation(groups=Name3.class)
String name;
@CheapValidation(groups=Surname1.class)
@ExpensiveValidation(groups=Surname2.class)
@VeryExpensiveValidation(groups=Surname3.class)
String surname;
public interface Name1 {}
public interface Name2 {}
public interface Name3 {}
@GroupSequence({Name1.class, Name2.class, Name3.class})
public interface Name {}
public interface Surname1 {}
public interface Surname2 {}
public interface Surname3 {}
@GroupSequence({Surname1.class, Surname2.class, Surname3.class})
public interface Surname {}
}
然后使用以下方法进行验证:
Then validate with:
validator.validate(myAccountBean,
AccountBean.Name.class, AccountBean.Surname.class)
关键是要有两个完全独立的组序列.
The key is to have two entirely independent group sequences.
不幸的是,看来您必须明确列出要验证的所有字段的组.我无法使其与默认" @GroupSequence一起使用.任何人都可以对此进行改进吗?
Unfortunately, it seems you must explicitly list the groups for all the fields you want to validate. I wasn't able to get it working with a 'default' @GroupSequence. Can anyone improve on this?
这篇关于JSR 303中的GroupSequence和有序评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!