5
votes

Formik + yup validation with .test() triggers on change on every field

example: i have a validation schema:

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

render function on my react component looks like:

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

so after every single field changed I receive messages from all .test() validators in console:

email registration runs
other validation runs

versions: react: 16.13.1 formik: 2.1.4 yup: 0.28.4

1
Oh wow, it's been a year, I have the similar feature like yours. But I'm out of luck. I can't seem to find any right answer. yup also didn't accept validation chain. Have you find your own solution now? @JustillusionIrfandy Jip
Are find any solution for this I am also stuck in the same @JustillusionGokulram

1 Answers

0
votes

By default formik validates after change, blur and submit events. Your code disables validation after change events with validateOnChange={false}. In order to only validate on submit events, try setting validateOnBlur to false too.

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