score:13

Accepted answer

You require age to be of type object, but set it the value of the selected option. That is what triggers your wrong validation. Here is how to fix your validation:

  1. If you want to keep age to be an object, change your schema to the following:
const Schema = Yup.object().shape({
    age: Yup.object().shape({
        label: Yup.string().required("Required"),
        value: Yup.string().required("Required")
    })
});

else set it to the following:

const Schema = Yup.object().shape({
    age: Yup.string()
});
  1. Update your onChange on the Select component to set the value to the option instead of the option.value if you want to use the object in your schema validation.
<Select
    { ... }
    value={field.value} // This can be set like this as a result of the change
    onChange={option => form.setFieldValue(field.name, option)}
/>

That should get it to work.

score:1

Yup Validation Schema

 const validationSchema = function (values) {
  return Yup.object().shape({  
    courseId: Yup.string().required("Required").nullable()
  })
}

React-select custom class component

import React from 'react'
import Select from 'react-select'

class SingleSelectField extends React.Component {
constructor(props) {
super(props);
}

handleChange = (item) => {
if(item)
  this.props.onChange(this.props.type, item.value);
else
  this.props.onChange(this.props.type, "");
};

handleBlur = () => {
  this.props.onBlur(this.props.type, true);
};

render() {

const defaultValue = (options, value) => {
  return options ? options.find(option => option.value === value) : "";
};

return (
<div>
<Select
options={this.props.options}
onChange={this.handleChange}
onBlur={this.handleBlur}
value={defaultValue(this.props.options, this.props.value)}
isClearable
/>
{!!this.props.error && this.props.touched && (
 <div style={{ color: "red", marginTop: ".5rem" }}>
  {this.props.error}
 </div>
 )}
 </div>  
 )}
}

export { SingleSelectField as default };

Related Query

More Query from same tag