首页 > 解决方案 > 如何在 Yup 结果中跳过空字符串?

问题描述

我想跳过空字符串作为是的结果。

我使用这个架构:

const schema = yup.object().shape({
  req: yup.string().required(),
  notReq: yup.string().notRequired().transform(v => v || undefined)
}).required();

const result = schema.cast({ req: 'Hello', notReq: '' });

我想看看下一个结果:

{ req: 'Hello', notReq: 'Bob' } -> { req: 'Hello', notReq: 'Bob' }
{ req: 'Hello', notReq: '' } -> { req: 'Hello' }

但是第二个例子我得到了错误

TypeError: The value of notReq could not be cast to a value that satisfies the schema type: "string". 

标签: javascriptyup

解决方案


推荐阅读