react-select - 无法使用带有 Yup 库的 Formik 验证反应选择
问题描述
我需要使用 Formik 和 Yup 验证 Select 选项和其他一些字段。实际上其他字段正在验证但 react-select 不能。我尝试了一些在线代码没有帮助。我的代码是这样的
我的是的规则
export const validationRules = Yup.object().shape({
name: Yup.string().required('Customer name required'),
email: Yup.string()
.email('Invalid email')
.required('Customer email required'),
geography: Yup.object().required('Please select Geography'),
});
我的选择选项是
const geography = [
{ code: 'US', label: 'US', id: 1 },
{ code: 'SG', label: 'SG', id: 2 },
{ code: 'AUS', label: 'AUS', id: 3 },
{ code: 'OTHER', label: 'OTHER', id: 4 },
];
初始数据是
const [intialData, setintialData] = useState({
name: '',
email: '',
geography: {},
});
我正在渲染这样
return(
<Formik
initialValues={intialData}
validationSchema={validation rules}
onSubmit={onSaveData}
>
{({ errors, setFieldValue, setFieldTouched, values, handleChange }) => (
<Form noValidate>
<div className="row">
<div className="col">
<label className="col-form-label-sm">Customer Name</label>
<Field type="text" className="form-control" name="name" />
{errors.name ? errors.name : ''}
</div>
<div className="col">
<label className="col-form-label-sm">Customer Email</label>
<Field type="email" className="form-control" name="email" />
{errors.email ? errors.email : ''}
</div>
</div>
<div className="row">
<div className="col">
<label className="col-form-label-sm">Geography</label>
<Select
name="geography"
onBlur={() => setFieldTouched('geography', true)}
onChange={option => setFieldValue('geography', option)}
options={geography}
/>
{errors.geography ? errors.geography : ''}
</div>
</div>
<div className="modal-footer">
<button type="submit" className="btn btn-primary">
Save changes
</button>
</div>
</Form>
)}
</Formik>
)
电子邮件和姓名字段没有经过 react-select 验证。所以我安慰了我的 Yup 错误对象,它只显示姓名和电子邮件验证,不显示地理位置。地理最初是初始数据中设置的空对象,请帮助我验证反应选择
解决方案
你应该object
像这样验证:
name: Yup.string().required('Customer name required'),
email: Yup.string()
.email('Invalid email')
.required('Customer email required'),
geography: Yup.object()
.shape({
id: Yup.string()
.required('Please, select office'),
})
您可以从以下位置获取错误:
{errors.geography ? errors.geography.id : ''}
推荐阅读
- docker - 我使用 Docker 在本地安装了 TensorFlow API(对象检测)。如何在 Jupyter Notebook 中使用这个包?
- spring-boot - 在 JMS 队列监听器 onMessage 方法中运行异步代码
- android - Jetpack Compose 失败并出现 NoClassDefFoundError:解析失败:Landroidx/compose/runtime/MutableStateKt;
- java - 如何折叠与主顶点相关的顶点列表?
- javascript - 从 iFramed 站点中删除 HTML Elemented
- dataframe - 根据条件更改 DataFrame 行中的值
- javascript - Vue传递预定值
- postgresql - SQL 错误 [42601]:错误:“。”或附近的语法错误 位置:115 -- 想法?错误使用 NEW 关键字?
- python - 单个图的多个 x 系列
- ruby-on-rails - Redis、Sidekiq 和 Heroku 应用程序