条件验证
有时候,我们需要基于其它参数的值才能确定当前参数应该用什么规则进行验证。从 1.2.0 开始,acr 使用简洁的 api 支持了这种验证方式。
when 方法
when(path, expect, chain)path参数名expect预期值chain:验证链
const rules = {
type: acr.string().required().in([ 'personal', 'common' ]),
age: acr.when('type', 'personal', () => {
return acr.string().required().min(18);
}),
};
// 抛出错误,age 必填
await acr.validate({
type: 'personal',
}, rules);
// 抛出错误,age 不能小于 18
await acr.validate({
type: 'personal',
age: 16,
}, rules);
// 通过
await acr.validate({
type: 'common',
age: 16,
}, rules);还可以使用 when 的重载方法来实现复杂条件的验证:
expect预期值chain:验证链
other 方法
other 方法只接受一个闭包作为参数,闭包返回值为一个验证链。从逻辑上来说,other 包含 when 没有包含的所有可能,因此,无论声明顺序是怎样,other 总是在所有条件之后执行,并且多次调用 other 只有最后一次有效。
多条件验证
在 when 方法后面,可以连接多个 when 方法,来实现更加复杂的条件验证。
多个参数联合验证
一个参数值的匹配,可以满足大多数情况的需求,针对一些极端条件,第一个参数可以提供闭包,返回一个 boolean 值来确定是否满足条件。
异步条件
当第一个参数为闭包时,支持使用异步方法来判断是否符合条件。
Last updated