Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do the yup validation for react-select

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.

like image 799
Allu Manikyam Avatar asked Mar 01 '19 05:03

Allu Manikyam


1 Answers

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

  • change topics to topic
  • change topic validation type from array to string
    • replace max with required
    • add ensure to default to empty string to handle selected value being cleared (https://github.com/jquense/yup#stringensure-schema)
  • 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{" "}
like image 137
lecstor Avatar answered Oct 19 '22 13:10

lecstor