I am using Material UI's Autocomplete multiple TextField, React Hook Form, and Yup to validate the form inputs.
When I use Yup.string() for the daysOfWeek, even if I have values selected, it shows the error message. However, if I change it to Yup.array(), the following error is displayed...
daysOfWeek must be a
arraytype, but the final value was:null(cast from the value""). If "null" is intended as an empty value be sure to mark the schema as.nullable()
Is there a way I can use Yup to validate Material UI's Autocomplete multiple TextField? Thank you in advance!
This is my relevant code...
const [selected, setSelected] = useState([]);
const validationSchema = Yup.object().shape({
daysOfWeek: Yup.string()
.required("Days of the week are required")
});
const {
formState: {errors},
handleSubmit,
register
} = useForm({
resolver: yupResolver(validationSchema)
});
<Autocomplete
disableClearable
disablePortal
filterSelectedOptions
multiple
getOptionDisabled={(option) => option.disabled ? true : false}
getOptionLabel={(option) => option.label}
id="days-autocomplete"
onChange={(event, value) => onOptionsChange(event, value)}
options={daysOfWeekSuggestions}
renderInput={(params) => <TextField
required
error={errors.daysOfWeek ? true : false}
id="daysOfWeek"
label="Days of the week"
name="daysOfWeek"
type="search"
{...params}
{...register("daysOfWeek")}
/>}
value={selected}
/>
<Typography color="error" sx={errorSx} variant="inherit">{errors.daysOfWeek?.message}</Typography>