mongoose typeError:分支不是一个函数,使用yup进行验证

sxpgvts3  于 2023-06-23  发布在  Go
关注(0)|答案(1)|浏览(87)

当尝试使用Yup库进行验证时,以下函数中会抛出错误“分支is not a function”(我已经注解掉了schema.validate函数,在这种情况下,我的代码可以工作,但scheme不能工作):

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',
    });
  }
};

即使代码中没有名为“分支”的函数或变量,并且所有的依赖项都被正确导入。有人能帮我找出这个错误的根本原因并提出一个可能的解决方案吗?

pgx2nnw8

pgx2nnw81#

你最近把yup升级到v1+了吗?它显示为.when() API has changed,如果使用旧语法,则会出现该错误。
您可以更改为使用以下语法:

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

等等的。

相关问题