我有点困惑 yup
正在工作。
我有以下模式来验证寄存器
export const registerValidationSchema = yup.object().shape({
first_name: yup.string().trim().required(),
last_name: yup.string().trim().required(),
date_of_birth: yup.date().required().test('DOB', 'You must be at least 18 to register', value => {
return value.setFullYear(value.getFullYear() + 18) < Date.now()
}),
email: yup.email().trim().required()
});
当要验证的对象如下时
const data = {
email: "john.doe@company.com"
}
验证将崩溃,因为 value
未定义且函数 value.setFullYear
将失败。但为什么?我假设 yup 会在 .required()
上停止这条线部分并转到下一个属性。
我知道这个问题可以通过添加 if(!value) return false;
来解决里面.test()
但是所需功能的意义何在?
来自 yup 文档:
string.required(message?: string | function): 架构
与所需的 mixed() 模式相同,除了空字符串也被视为“缺失”值。
mixed.required(message?: string | function): 架构
将架构标记为必需,这将不允许将未定义或空值作为值。请注意,除非模式被标记为 nullable(),否则 null 值将被视为类型错误,而不是缺失值。将模式标记为 mixed().nullable().required() 将 null 视为缺失。
所以我将其读作 undefined
, null
或 ''
.required()
上的值应该失败规则。
最佳答案
代替电子邮件:yup.email().trim().required()
试试 email: yup.string().trim().email().required()
const registerValidationSchema = yup.object().shape({
first_name: yup.string().trim().required(),
last_name: yup.string().trim().required(),
date_of_birth: yup.date().required().test('DOB', 'You must be at least 18 to register', value => {
return value.setFullYear(value.getFullYear() + 18) < Date.now()
}),
// email: yup.email().trim().required
// modified
email: yup.string().trim().email().required()
})
const data = {
first_name: "john",
last_name: "deo",
date_of_birth: "12-jan-2000",
email: " john.doe@gamil.com "
}
// validating schema
registerValidationSchema.isValid(data)
.then(r => console.log(r))
.catch(e => console.log(e))
关于javascript - 是的,当 .required() 为 false 时,会继续在同一个属性上运行验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75015939/