gpt4 book ai didi

javascript - 如何通过单个 react 选择正确使用 Yup 模式?

转载 作者:行者123 更新时间:2023-12-01 01:02:02 25 4
gpt4 key购买 nike

我正在使用 react-selectFormikYup 来验证我的表单,但由于某种原因我的验证不起作用。我的架构如下所示:

const Schema = Yup.object().shape({
age: Yup.object().shape({
label: Yup.string().required("Required"),
value: Yup.string().required("Required")
})
});

我的数据如下所示:

export const ageOptions = [
{ value: 0.1, label: "Not born yet" },
{ value: 0.3, label: "Baby - 0 to 3 months" },
{ value: 0.6, label: "Baby - 3 to 6 months" },
{ value: 0.12, label: "Baby - 6 to 12 months" },
{ value: 0.18, label: "Baby - 12 to 18 months" },
{ value: 0.24, label: "Baby - 18 to 24 months" },
{ value: 2, label: "2 years" },
{ value: 3, label: "3 years" },
{ value: 4, label: "4 years" },
{ value: 5, label: "5 years" },
{ value: 6, label: "6 years" },
{ value: 7, label: "7 years" },
{ value: 8, label: "8 years" },
{ value: 9, label: "9 years" },
{ value: 10, label: "10 years" },
{ value: 11, label: "11 years" },
{ value: 12, label: "12 years" },
{ value: 13, label: "13 years" },
{ value: 14, label: "14 years" }
];

当我在 UI 内的选择中选择一个选项时,返回以下错误:

age must be a `object` type, but the final value was: `null` (cast from the value `0.6`). If "null" is intended as an empty value be sure to mark the schema as `.nullable()`

如何使验证正确进行?

Link to sandbox

最佳答案

您要求 ageobject 类型,但将其设置为所选选项的值。这就是触发您错误验证的原因。以下是修复验证的方法:

  1. 如果您希望将 age 保留为一个对象,请将架构更改为以下内容:
const Schema = Yup.object().shape({
age: Yup.object().shape({
label: Yup.string().required("Required"),
value: Yup.string().required("Required")
})
});

否则将其设置为以下内容:

const Schema = Yup.object().shape({
age: Yup.string()
});
  • 更新 Select 组件上的 onChange,将值设置为 option 而不是 option.value 如果您想在架构验证中使用该对象。
  • <Select
    { ... }
    value={field.value} // This can be set like this as a result of the change
    onChange={option => form.setFieldValue(field.name, option)}
    />

    这应该可以让它工作。

    关于javascript - 如何通过单个 react 选择正确使用 Yup 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55978417/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com