首页
/ Yup条件验证的正确使用方式

Yup条件验证的正确使用方式

2025-05-08 11:08:23作者:丁柯新Fawn

Yup是一个流行的JavaScript对象模式验证库,广泛应用于表单验证和数据校验场景。在实际开发中,条件验证是一个常见需求,但很多开发者在使用Yup的when方法时会遇到各种问题。

条件验证的基本语法

Yup提供了.when()方法来实现条件验证,其基本语法结构如下:

yup.string().when("依赖字段名", {
  is: 条件判断,
  then: 满足条件时的验证规则,
  otherwise: 不满足条件时的验证规则
})

常见错误与修正

很多开发者会直接这样写:

yup.string().when("role", {
  is: "teacher",
  then: yup.string().required("School is required"),
  otherwise: yup.string().notRequired(),
})

这在Yup 0.32.11版本中可以工作,但在1.4及以上版本会报错"branch is not a function"。正确的写法应该是:

yup.string().when("role", {
  is: "teacher",
  then: (schema) => schema.required("School is required"),
  otherwise: (schema) => schema.notRequired(),
})

复杂对象的条件验证

对于嵌套对象的条件验证,同样需要遵循上述原则。例如,根据class字段的值来验证不同的subject结构:

subjects: yup.object().shape({}).when('class', {
  is: (val) => val === 9 || val === 10,
  then: (schema) => yup.object().shape({
    mil: yup.string().required('Mil is required'),
    sil: yup.string().required('Sil is required'),
    comp_sub_1: yup.string().required('comp sub 1 is required'),
    // 其他字段...
  }),
  otherwise: (schema) => yup.object().shape({
    comp_sub_1: yup.string().required('comp sub 1 is required'),
    elective_1: yup.string().required('elective_1 is required'),
    // 其他字段...
  })
})

最佳实践建议

  1. 始终使用函数形式的thenotherwise回调
  2. 对于复杂的条件判断,可以使用函数形式的is参数
  3. 保持验证规则的清晰和可维护性
  4. 对于大型表单,考虑将验证规则拆分为多个模块

通过遵循这些原则,可以确保Yup的条件验证在各种场景下都能正常工作,同时保持代码的可读性和可维护性。

登录后查看全文
热门项目推荐
相关项目推荐