React + Formik + 是的异步验证

Jus*_*ion 5 reactjs yup formik

Formik + yup 验证与 .test() 触发每个字段的更改

示例:我有一个验证架构:

const schemaValidation = yup.object().shape({
  name: yup.string().required(),
  email: yup.string().email().required()
    .test( // it runs even if previous validation failed!
      'checkEmailExists', 'email already taken.',
      // it triggers on every onBlur
      email => { console.log('email registration runs') return Promise.resolve(true)}
    ),
  other: yup.string().required()
     .test(
      'checkOthers', 'error', 
      val => {console.log('other validation runs'); return Promise.resolve(true)}
    )
})
Run Code Online (Sandbox Code Playgroud)

我的反应组件上的渲染功能如下所示:

...
render () {
 return(
  <Formik
    validateOnChange={false}
    validateOnBlur={true}
    initialValues={{
      name: '',
      email: '',
      other: ''
    }}
    validationSchema={schemaValidation}
    onSubmit={this.handleSubmit}
  >
    {(props) => (
    <Form>
      <div className="field">
        <Field className="input" type="email" name="email" placeholder="Email" />
        <ErrorMessage name="email" />
      </div>

      <div className="field">
        <Field className="input" type="text" name="name" placeholder="Name"/>
        <ErrorMessage name="name" />
      </div>

      <div className="field">
        <Field className="input" type="text" name="other" placeholder="Other"/>
        <ErrorMessage name="other" />
      </div>

      <button type="submit">Submit</button>
    </Form>
    )}
  </Formik>
 )

Run Code Online (Sandbox Code Playgroud)

因此,在每个字段更改后,我都会在控制台中收到来自所有 .test() 验证器的消息:

email registration runs
other validation runs
Run Code Online (Sandbox Code Playgroud)

版本:反应:16.13.1 格式:2.1.4 是的:0.28.4

小智 0

默认情况下,formik 在更改、模糊和提交事件后进行验证。您的代码在更改事件后禁用验证validateOnChange={false}。为了仅验证提交事件,也尝试设置validateOnBlurfalse

https://jaredpalmer.com/formik/docs/guides/validation#when-does-validation-run https://jaredpalmer.com/formik/docs/api/formik#validateonblur-boolean