default
default(value, [ctx])
作用
设置当被检测值为undefined | null | NaN
时,validate
和validateSilent
方法的返回值。
参数
value
(*) -validate
和validateSilent
默认返回值。推荐但不必须为number
类型。当value
为函数时,则设置函数的返回值为默认值,函数有一个参数:被检测原始值——undefined
,null
或NaN
.[ctx]
(*) - 当value
为函数时的执行上下文this
。
示例
const schema1 = racoon.number().allowNaN().default(1);
schema1.validate(undefined); // pass, 返回 1
schema1.validate(null); // pass, 返回 1
schema1.validate(NaN); // pass, 返回 1
const schema2 = racoon().number().allowNaN().default((val) => {
if (val === undefined) {
return 1;
}
if (val === null) {
return 2;
}
return 3; // 此时 val 必定为 NaN
});
schema2.validate(undefined); // pass, 返回 1
schema2.validate(null); // pass, 返回 2
schema2.validate(NaN); // pass, 返回 3
最后更新于
这有帮助吗?