1-常用约束规则RuleSource的设置方法
例如:
addRules(new Rules(ProgramFeeItem.class){
protected void initRules() {
add("rateClass", all(new Constraint[] { required() })); //required表示,不可为空
add("remark", rules.maxLength(250)); //maxLength约束最大长度250
addMoneyRule(this,"payingSumFee");
}
});
2-自定义约束规则方法:
创建AbstractPropertyContraint对象,并实现test和toString方法,test方法用户定义约束规则 ,toString方法用户设置异常信息
例如:
addRules(new Rules(ProgramFeeItem.class){
protected void initRules() {
addMoneyRule(this,"payingSumFee"); //addMoneyRule自定义约束规则
}
});
protected void addMoneyRule(Rules rules,final String datePath){
rules.add(new AbstractPropertyConstraint(datePath) {
@Override
protected boolean test( //规则检测方法
PropertyAccessStrategy domainObjectAccessStrategy) {
//通过策略获取payingSumFee的值
Money amount = (Money) domainObjectAccessStrategy.getPropertyValue(datePath);
//自定义规则Money的范围
return amount.gte(new Money(-9999999999.99D))&&amount.lte(new Money(9999999999.99D));
}
@Override
public String toString() {//用户设置异常返回码
return Application.services().getApplicationContext()
.getMessage("gte.-9999999999.99.and.lte.9999999999.99",
new Object[] {},
"gte.-9999999999.99.and.lte.9999999999.99",
Locale.getDefault());
}
});
}
3-两控件联动约束规则设置方法:
使用RequireAIfBTrue对象实现,
public RequireAIfBTrue(String a, String b, Constraint aConstraint, Constraint bContraint,String msgKey) {
其中
a 要求约束对应的属性
b 要求约束的前提约束对应的属性
aConstraint Constraint 要求约束
bContraint Constraint 要求约束的前提约束
msgKey String 国际化信息
例如:
addRules("receipt",new Rules(ProgramWorkOrder.class) {
protected void initRules() {
add(new RequireAIfBTrue("failureReason", "taskResult", required(),
new Constraint() { //指定约束规则
public boolean test(Object argument) { //约束规则设置
TaskResult result = (TaskResult) argument;
if (result != null && result.ordinal() == TaskResult.UNSUCCESS.ordinal()) {
return true;
}
return false;
}
}, "required")); //required国际化信息
}
});