Member-only story

Fomik does not validate field onPaste, unless you click outside of field (blur)

Ben Grunfeld
2 min readMay 29, 2023

Recently I had a nasty bug when using Formik with React and Next.JS.

When you added a contact from Android, a new value would be pasted into an input field. Unfortunately Formik did not realize that this was happening, and did not validate the field. We needed validation to run on paste.

tl;dr — my mega-hacky solution:

const handlePaste = () => {
setTimeout(() => {
emailRef.current.childNodes[1].firstChild.blur()
emailRef.current.childNodes[1].firstChild.focus()
}, 300)
}

The thing is, validation would run if you clicked outside of the field — i.e. onBlur.

I tried using formik.validateForm, but no dice.

On further inspection of formik.values, I found that the new value was not being registered in Formik’s state, so there was nothing to validate.

{ firstName: "", lastName: "", recipientEmail: "" }

I tried using setFieldValue to overcome this, but Formik’s state would still not update and validation would not run.

I then tried using enableReinitialize and updating the value of recipientEmail via setState , but this didn’t work either.

I threw everything I could at this, and even asked my lead dev for help, but nothing worked.

--

--

Ben Grunfeld
Ben Grunfeld

Written by Ben Grunfeld

I’m a Front End Engineer who loves React, NextJS, and GraphQL. Looking for a developer in #Israel? Contact me at: https://www.linkedin.com/in/bengrunfeld/

No responses yet