我需要使用Formik和Yup来验证Select选项和其他一些字段。实际上其他字段正在验证,但是react-select无法。我尝试了一些在线代码,但没有帮助。 我的代码是
我的Yup规则
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错误对象 其仅显示名称和电子邮件验证,而不显示地理位置。 地理位置最初是在初始数据中设置的空对象,请帮助我验证react-select
答案 0 :(得分:0)
您应像这样验证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 : ''}
答案 1 :(得分:0)
您好,这是解决问题及其工作方式的方法。
<Select
onBlur={() => setFieldTouched('gerography', true)}
onChange={(option, e) => {
handleChange('gerography', option);
this.onGeographyChange(option); //set values to state
setFieldValue('gerography', option);
}}
options={gerographys}
name="gerography"
value={state.gerography}
/>