firstName: yup
.string()
.test(
'len',
'can be empty or with string at least 2 characters and not more than 10',
(val) => val != undefined && (val.length == 0 || (val.length >= 2 && val.length <= 10) )
)
在这种情况下,长度最小值 2 和最大值 10 有效,但是当为空时标记为错误,我尝试使用
val.length == 0
你好,你可以这样做
const yup = require("yup");
const firstName = "";
const schema = yup
.string()
.test(
"len",
"can be empty or with string at least 2 characters and not more than 10",
(val) => {
if (val === undefined) {
return true;
}
return val.length === 0 || (val.length >= 2 && val.length <= 10);
}
);
schema
.validate(firstName)
.then((response) => console.log(response))
.catch((err) => console.log(err));
通过单独的未定义检查修复
firstName: yup
.string()
.test(
'len',
'can be empty or with string at least 2 characters and not more than 10',
(val) => {
if (val == undefined) {
return true;
}
return ((val.length == 0 || (val.length >= 2 && val.length <= 10)))
}
),
全局函数,
export const minLengthValidation = (value: string | undefined, limit: number | undefined = 3) => {
if (value && value.length < limit) {
return false
}
return true
}
调用了该函数,
nick_name: yup
.string()
.max(50, 'Nickname must be less than 50 characters!')
.test('min-length', 'Nickname must be greater than 3 characters!', value => minLengthValidation(value))
.required('Nickname is required.'),