首页 > 解决方案 > 无法使用带有 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 错误对象,它只显示姓名和电子邮件验证,不显示地理位置。地理最初是初始数据中设置的空对象,请帮助我验证反应选择

标签: react-selectformikyup

解决方案


你应该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 : ''}

推荐阅读