我发现了对react-select(multiple select)的yup验证。请引用链接select multiple items of react-select validation in yup。但是我不需要使用yup进行多重选择验证。我需要对使用yup的react-select进行基本验证。使用yup实现 react 选择验证。

我如何使用yup来实现它。请帮我解决这个问题。

提前致谢。最好的答案将不胜感激。

最佳答案

https://codesandbox.io/s/03zxq01okp

  • topics更改为topic
  • 将主题验证类型从数组更改为字符串
  • max替换required
  • ensure默认添加为空字符串以处理被清除的选定值(https://github.com/jquense/yup#stringensure-schema)
  • mapPropsToValues topic类型从数组更改为字符串
  • 使用valuetopic作为有效载荷

  • 差异:
    15,22c15,17
    <     topics: Yup.array()
    <       .max(1, "Pick at least 3 tags")
    <       .of(
    <         Yup.object().shape({
    <           label: Yup.string().required(),
    <           value: Yup.string().required()
    <         })
    <       )
    ---
    >     topic: Yup.string()
    >       .ensure()
    >       .required("Topic is required!")
    26c21
    <     topics: []
    ---
    >     topic: ""
    31c26
    <       topics: values.topics.map(t => t.value)
    ---
    >       topic: values.topic.value
    72c67
    <         value={values.topics}
    ---
    >         value={values.topic}
    75,76c70,71
    <         error={errors.topics}
    <         touched={touched.topics}
    ---
    >         error={errors.topic}
    >         touched={touched.topic}
    107c102
    <     this.props.onChange("topics", value);
    ---
    >     this.props.onChange("topic", value);
    112c107
    <     this.props.onBlur("topics", true);
    ---
    >     this.props.onBlur("topic", true);
    118c113
    <         <label htmlFor="color">Topics (select at least 3) </label>
    ---
    >         <label htmlFor="color">Topic</label>
    156c151
    <       <code>topics</code> that uses Jed Watson's{" "}
    ---
    >       <code>topic</code> that uses Jed Watson's{" "}
    

    10-06 04:26