检查字段是否有效 Formik React JS

Check if a field is valid Formik React JS

我在一个项目中使用 FormikYup

我正在创建一个多步骤表单。当用户点击下一步按钮时, 如果第一步的输入有效,我想显示第二步的输入。否则他应该留在第一步。

是否有检查输入是否有效的函数?

<Formik
initialValues={{
  name: '',
  kitchenName: '',
  phone: '',
  email: '',
  address: {
    street: '',
    city: '',
    postalCode: '',
    country: '',
  },
}}
validationSchema={Yup.object({
  name: Yup.string().min(3).max(30).required(),
  kitchenName: Yup.string().min(3).max(40).required(),
  phone: Yup.string().min(10).max(13).required(),
  email: Yup.string().email().required(),
  street: Yup.string().required(),
  city: Yup.string().required(),
  postalCode: Yup.number().required(),
  country: Yup.string().required(),
})}
onSubmit={(values, { isSubmitting, resetForm }) => {
  console.log(values);
}}
>
{(props) => (
  <Form>
    <div className='step-1 d-none'>
      <TextInput label='Your Name' type='text' name='name' />
      <TextInput
        label='Kitchen Name'
        type='text'
        name='kitchenName'
      />
      <TextInput label='Phone or Whatsapp' type='text' name='phone' />
      <TextInput label='Email Address' type='text' name='email' />
      <button type='button' className='cta-btn cta-btn-primary'>
        Next
      </button>
    </div>
    <div className='step-2'>
      <TextInput label='Street Address' type='text' name='street' />
      <TextInput label='City' type='text' name='city' />
      <TextInput label='Postal Code' type='text' name='postalCode' />
      <TextInput label='Country' type='text' name='country' />
      <button
        type='button'
        className='btn btn-dark px-3 shadow-none mr-3'
      >
        Back
      </button>
      <button type='button' className='cta-btn cta-btn-primary'>
        Apply
      </button>
    </div>
  </Form>
)}
</Formik>

是的,有。您可以使用 Field-level Validation:

Formik supports field-level validation via the validate prop of / components or useField hook. This function can be synchronous or asynchronous (return a Promise). It will run after any onChange and onBlur by default

您必须为每个字段(或共享字段)创建一个验证函数,并通过 validate 属性将其传递给该字段。一个简短的例子:

 function validateEmail(value) {
   let error;
   if (!value) {
     error = 'Required';
   } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
     error = 'Invalid email address';
   }

   return error;
 }

<Form>
  <Field name="email" validate={validateEmail} />
</Form>;