【问题标题】:Check if a field is valid Formik React JS检查字段是否有效 Formik React JS
【发布时间】:2021-03-18 09:58:43
【问题描述】:

我正在一个项目中使用 FormikYup

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

是否有检查输入是否有效的功能?

<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>

【问题讨论】:

    标签: reactjs next.js formik yup


    【解决方案1】:

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

    Formik 通过 / components 的 validate 属性或 useField 钩子支持字段级别的验证。这个函数可以是同步的或异步的(返回一个 Promise)。默认情况下,它将在任何 onChange 和 onBlur 之后运行

    您必须为每个字段(或共享字段)创建一个验证函数,并通过 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>;
    

    【讨论】:

      猜你喜欢
      • 2019-09-10
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2021-11-10
      相关资源
      最近更新 更多