Yup 验证表单时如何动态添加或移除验证规则?

轩辕淑丽 阅读 2

我在用 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()
  })
});
我来解答 赞 0 收藏
二维码
手机扫码查看
1 条解答
令狐秀玲
你的代码写法基本是对的,但注意 when 的比较要用函数而不是直接字符串。试试这样改:

let baseSchema = yup.object({
role: yup.string().required(),
school: yup.string().when('role', {
is: value => value === 'student',
then: schema => schema.required(),
otherwise: schema => schema.notRequired()
})
});


应该能用,我昨晚刚调过类似的,累死我了...
点赞
2026-03-30 00:00