How do the yup validation for react-select

Allu Manikyam picture Allu Manikyam · Mar 1, 2019 · Viewed 11.2k times · Source

I found the yup validation for react-select(multiple select).Please refer the link select multiple items of react-select validation in yup.But i don't need multiple selection validation using yup.I need a basic validation for react-select using yup.I tried but i failed to implement the react-select validation using yup.

How can I achieve it using yup.Please help me out this problem.

Thanks in advance. Best answer will be appreciated.

Answer

lecstor picture lecstor · Mar 4, 2019

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

  • change topics to topic
  • change topic validation type from array to string
  • change mapPropsToValues topic type from array to string
  • use value of topic for payload

Diff:

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{" "}