代码之家  ›  专栏  ›  技术社区  ›  Sandy

如何在yup中使用oneOf进行验证

yup
  •  0
  • Sandy  · 技术社区  · 2 年前

    我认为这是一个简单的验证,使用 oneOf

    const schema = Yup.mixed()
      .oneOf([
        {
          error: `EmailOrPasswordInvalid`,
        },
        {},
      ])
      .required();
    

    ... 后来

    const isValid = schema.isValidSync({ error: `EmailOrPasswordInvalid` });
    console.log(isValid); // false
    

    1 回复  |  直到 2 年前
        1
  •  0
  •   angol    2 年前

    我相信你可能误解了oneOf函数的工作原理。

    下面是一个来自Grepper帖子的示例(归功于Fustinato):

    // mixed.oneOf(arrayOfValues: Array<any>, message?: string | function): Schema Alias: equals
    // Whitelist a set of values. Values added are automatically removed from any blacklist if they are in it. The ${values} interpolation can be used in the message argument.
    
    // Note that undefined does not fail this validator, even when undefined is not included in arrayOfValues. If you don't want undefined to be a valid value, you can use mixed.required.
    
    let schema = yup.mixed().oneOf(['jimmy', 42]);
    
    await schema.isValid(42); // => true
    await schema.isValid('jimmy'); // => true
    await schema.isValid(new Date()); // => false
    

    希望这能帮助你理解事情。

    编辑: 在进一步的回复和查找中,似乎您试图做的事情可能不可能?Src: https://github.com/jquense/yup/issues/1393

    推荐文章