formik: validateField not working

๐Ÿ› Bug report

When calling validateField the field is not validated

Current Behavior

Here is a repository to checkout and click the button labeled โ€œNext Stepโ€ which is supposed to validate field โ€œemailโ€ https://github.com/cyberprodigy/formik-single-field-validation-bug

Expected behavior

When the method validateField is called it should display that the field is required

Reproducible example

Checkout https://github.com/cyberprodigy/formik-single-field-validation-bug execute `npm start`` Observe that no validation is happening

Suggested solution(s)

It should display the error when validateField is invoked. You can trigger focus() followed by blur() to obtain the desired behaviour, but that is not a solution

Additional context

Your environment

Software Version(s)
Formik 1.5.8
React 16.9.0
TypeScript
Browser
npm/Yarn
Operating System Mac Mojave

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 1
  • Comments: 18 (7 by maintainers)

Most upvoted comments

Also running into this in a form with a validationSchema but no validate.

Looks like if there is no validate function on a field, it just calls Promise.resolve() https://github.com/jaredpalmer/formik/blob/master/src/Formik.tsx#L426

Also the full TypeError is "_this.fields[field].props.validate is not a function"

I wanted to do a programmatic validation on a single field (nested object inside of an array) using validationSchema and set/clear field errors based on validation result.

yup.reach(schema, 'path.to.field').validate(fieldValue) was throwing an error: Uncaught TypeError: Cannot read property 'resolve' of undefined

I ended up with this handler as a workaround:

const handleFinishEdit = (viewValue) => {
  props.form.setFieldValue(fieldName, viewValue)
  
  // use lodash/set because props.form.values are stale
  const updatedFormValues = set(
    props.form.values,
    fieldName,
    viewValue
  )
  
  yourYupSchema
     // Don't forget to add context if you use it
    .validateAt(fieldName, updatedFormValues, {context: updatedFormValues })
    .then(() => props.form.setFieldError(fieldName, null))
    .catch(err => props.form.setFieldError(fieldName, err.message)
  }

Hope that helps someone with a similar issue:)

P.S. this should not be treated as a substitute for an actual formik validation, see: https://github.com/jaredpalmer/formik/issues/1278#issuecomment-461036355 https://github.com/jaredpalmer/formik/issues/1309

Good find @johnrom! Iโ€™ll give this fix a try on the v2 branch this weekend.