我有一个使用单值反应选择创建的必需选择菜单。如果用户没有从选择菜单中选择任何选项并单击保存按钮,我想显示错误。
下面是我的代码,
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>
</>
);
}
我不确定如何对反应选择单个值进行验证。有人可以帮我解决这个问题。谢谢。我是使用 react 和 yup 验证的新手。
下面的编辑 是我尝试过的
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');
});
但这不起作用。