i have a required select menu that is created using single value react select.
if user doesnt select any option from select menu and clicks save button i want to display error.
below is my code,
const validationSchema = Yup.object().shape({
[DESCRIPTION_KEY]: Yup.string(),
[NAME_KEY]: Yup.string()
.max(256, 'The name should not be longer than 256 characters')
.required('Please fill out this field.'),
});
const options = [
{ value: 'option1', label: 'option1' },
{ value: 'option2', label: 'option2' },
{ value: 'option3', label: 'option3'},
];
const Parent= ({ formikBag }: { formikBag: FormikProps}) => {
const handleSave = () => {
const promiseArr = formFields.map(field =>
validationSchema.validateAt(field, values!).catch(e => e)
);
const validationsArr = await Promise.all(promiseArr);
const errorsArr = validationsArr.filter(
field => field instanceof ValidationError
);
if (!isEmpty(errorsArr)) {
errorsArr.forEach(fieldError => {
setFieldTouched && setFieldTouched(fieldError.path, true, true);
});
return;
}
return (
<>
<FormField
label="Name"
fieldId={NAME_KEY}
required
/>
<FormField
as="textarea"
label="Description"
fieldId={DESCRIPTION_KEY}
/>
<FormField label="single value select menu *" fieldId=
{SINGLE_SELECT}>
<Select //uses react select
id={field.name}
inputId={field.name}
onChange={(option: SelectOption) =>
form.setFieldValue(field.name, option.value)
}
options={options}
placeholder="Select single option"
value={options.filter(option => option.value ===
field.value)}
/>
)}
</FormField>
<button onClick={handleSave}>Save</button>
</>
);
}
I am not sure how to do validation for react select single value. could someone help me with this. thanks. i am new to using react and yup validation.
EDIT
below is what i have tried
const validationSchema = Yup.object().shape({
[DESCRIPTION_KEY]: Yup.string(),
[NAME_KEY]: Yup.string()
.max(256, 'The name should not be longer than 256 characters')
.required('Please fill out this field.'),
[SINGLE_SELECT]: Yup.string()
.required('Please selection an option');
});
but this doesnt work.
question from:
https://stackoverflow.com/questions/65835815/how-to-yup-validate-with-single-react-select 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…