核查的时候,其实就是怎么校验数据的正确还是错误,核查函数为静态类 MkValidators 内的所有静态函数
注意:
类MkValidators是版本 v1.4.5及之后改名的,之前为Checks
/**
* 核查对象
*/
public boolean check(Object object){}
/**
* 核查对象的某些属性
*/
public boolean check(Object object, String... fieldSet){}
/**
* 根据分组核查属性
*/
public boolean check(String group, Object object) {}
/**
* 核查分组中的对象的某些属性
*/
public boolean check(String group, Object object, String... fieldSet){}
/**
* 返回错误信息链
*/
public String getErrMsgChain() {}
/**
* 获取最后设置错误信息
*/
public String getErrMsg() {}
/**
* 核查对象失败抛异常
*/
public void validate(Object object) throws MkException
/**
* 核查对象指定属性失败抛异常
*/
public void validate(Object object, String ...fieldSet) throws MkException
/**
* 根据组核查对象失败抛异常
*/
public void validate(String group, Object object) throws MkException
/**
* 根据组核查对象指定属性失败抛异常
*/
public void validate(String group, Object object, String ...fieldSet) throws MkException
核查整个对象
那么会核查对象中的所有添加@Matcher注解(而且disable=false)的属性
核查某些属性
有些情况下,我们可能不是核查整个对象,而是可能核查某些属性,那么就可以使用核查某些属性的功能
@Data
@Accessors(chain = true)
public class TestEntity {
@Matcher(value = {"nihao", "ok"}, accept = false)
private String name;
@Matcher(range = "[12, 32]")
private Integer age;
@Matcher({"beijing", "shanghai"})
private String address;
}
def "测试指定的属性age"() {
given:
TestEntity entity = new TestEntity().setName(name).setAge(age)
expect:
def act = MkValidators.check(entity, "age");
Assert.assertEquals(result, act)
if (!act) {
println MkValidators.errMsg
}
where:
name | age | result
"nihao" | 12 | true
"ok" | 32 | true
"hehe" | 20 | true
"haohao" | 40 | false
}
核查某个组
对于一个属性,在不同的情况下,对这个属性值的要求可能不同,那么这个时候该怎么办呢,那么group属性就排上用场了
@Data
@Accessors(chain = true)
public class GroupEntity {
@Matchers({
@Matcher(range = "[50, 100]", accept = false),
@Matcher(group = "test1", range = "[12, 23]", accept = false),
@Matcher(group = "test2", range = "[1, 10]", accept = false)
})
private Integer age;
@Matchers({
@Matcher(value = {"beijing", "shanghai", "guangzhou"}),
@Matcher(group = "test1", value = {"beijing", "shanghai"}),
@Matcher(group = "test2", value = {"shanghai", "hangzhou"})
})
private String name;
}
def "测试指定分组指定属性"() {
given:
GroupEntity entity = new GroupEntity().setAge(age).setName(name)
expect:
def act = MkValidators.check("test1", entity, "age");
Assert.assertEquals(result, act)
if (!act) {
println MkValidators.errMsgChain
}
where:
age | name | result
10 | "shanghai" | true
12 | "beijing" | false
23 | "beijing" | false
50 | "beijing" | true
100 | "guangzhou" | true
}