我需要使用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
我需要使用Formik和Yup来验证Select选项和其他一些字段。实际上其他字段正在验证,但是react-select无法。我尝试了一些在线代码,但无济于事。我的代码,例如...
您应像这样验证object
:
您好,这是解决问题及其工作的方式。