Yup 验证表单时如何动态添加或移除验证规则?
我在用 Yup 做一个带条件验证的注册表单,比如用户选了“学生”身份才需要填学校字段。但我不确定怎么在运行时动态加或删验证规则,试过直接修改 schema 但好像没生效。
比如下面这样写,切换身份后学校字段还是必填,是不是哪里错了?
let baseSchema = yup.object({
role: yup.string().required(),
school: yup.string().when('role', {
is: 'student',
then: (schema) => schema.required(),
otherwise: (schema) => schema.notRequired()
})
});
when的比较要用函数而不是直接字符串。试试这样改:应该能用,我昨晚刚调过类似的,累死我了...