是的,验证将空字符串转换为默认值

Das*_*sto 5 node.js yup

在我的 Yup 模式中,我的 String 字段name允许您传入任何字符串、空字符串或什么都不传入。如果你传入一个字符串,它就会通过。如果你传入一个空字符串或什么都没有,我想转换为默认值。

这是我认为可以涵盖它的模式:

const mySchema = yup.object().shape({
  name: yup.string('Name must be a string').max(100, 'Name has a max of 100 characters').default('John Doe')
});
Run Code Online (Sandbox Code Playgroud)

但是,如果我传入一个空字符串'',它不会触发默认转换,它只是作为空字符串传递。我尝试添加required(),但如果我传递空字符串,这只会使该行失败。我已经尝试过nullable()trim()但似乎没有任何效果。

如何让默认值替换空字符串?

Das*_*sto 8

我最终添加了一个简单的方法来将空字符串转换为未定义,该方法将在默认情况下被拾取:

// Add method
yup.addMethod(yup.string, 'stripEmptyString', function () {
  return this.transform((value) => (value === '' ? undefined : value));
});

// Usage
const mySchema = yup.object().shape({
  name: yup.string('Name must be a string').stripEmptyString().default('John Doe')
});
Run Code Online (Sandbox Code Playgroud)