类型错误:分支不是使用 yup 进行验证的函数

Aze*_*eez 1 mongoose node.js express reactjs yup

当尝试使用 Yup 库进行验证时,以下函数中会抛出错误“branch is not a function”(我已注释掉 schema.validate 函数,在这种情况下我的代码可以正常工作,但使用 schema 则无法正常工作):


const schema = Yup.object({
  boundary: Yup.string().required('Boundary is required'),
  boundaryConstructionDate: Yup.string().when('boundary', {
    is: (value) => value === 'yes',
    then: Yup.string().required('Boundary construction date is required'),
    otherwise: Yup.string(),
  }),
  toilet: Yup.string().required('Toilet is required'),
  toiletConstructionDate: Yup.string().when('toilet', {
    is: (value) => value === 'yes',
    then: Yup.string().required('Toilet construction date is required'),
    otherwise: Yup.string(),
  }),
  payjal: Yup.string().required('Payjal is required'),
  ramp: Yup.string().required('Ramp is required'),
  rampConstructionDate: Yup.string().when('ramp', {
    is: (value) => value === 'yes',
    then: Yup.string().required('Ramp construction date is required'),
    otherwise: Yup.string(),
  }),
  divyangToilet: Yup.string().required('DivyangToilet is required'),
  divyangToiletConstructionDate: Yup.string().when('divyangToilet', {
    is: (value) => value === 'yes',
    then: Yup.string().required('DivyangToilet construction date is required'),
    otherwise: Yup.string(),
  }),
  floorTiles: Yup.string().required('Floor Tiles is required'),
  floorTilesConstructionDate: Yup.string().when('floorTiles', {
    is: (value) => value === 'yes',
    then: Yup.string().required('Floor Tiles construction date is required'),
    otherwise: Yup.string(),
  }),
  library: Yup.string().required('Library is required'),
  libraryConstructionDate: Yup.string().when('library', {
    is: (value) => value === 'yes',
    then: Yup.string().required('Library construction date is required'),
    otherwise: Yup.string(),
  }),
});



const validateWithYup = () => async (req, res, next) => {
  try {
    let object =  {
     boundary: 'no',
    boundaryConstructionDate: '',
    toilet: 'no',
    toiletConstructionDate: '',
    payjal: 'no',
    ramp: 'no',
    rampConstructionDate: '',
    divyangToilet: 'no',
    divyangToiletConstructionDate: '',
    floorTiles: 'no',
    floorTilesConstructionDate: '',
    library: 'no',
    libraryConstructionDate: ''
  };
    

    await schema.validate(object, { abortEarly: false });
    next();
  } catch (error) {
    console.log('ERROR HERE --->', error);
    return res.status(400).json({
      message: 'Validation error',
    });
  }
};
Run Code Online (Sandbox Code Playgroud)

即使代码中没有名为“branch”的函数或变量,并且所有依赖项都已正确导入。谁能帮助我确定此错误的根本原因并提出可能的解决方案?

Ben*_*ley 7

您最近将 yup 升级到 v1+ 了吗?看来.when()api已更改如果您使用旧语法,则会出现该错误

您可以更改为使用以下语法:

  ...
  boundaryConstructionDate: Yup.string().when('boundary', {
    is: (value) => value === 'yes',
    then: (schema) => schema.required('Boundary construction date is required'),
    otherwise: (schema) => schema,
  })
  ...
Run Code Online (Sandbox Code Playgroud)

ETC。