-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Validation runs on old value when onChange is called within onBlur #2106
Comments
This looks like it's the culprit formik/packages/formik/src/Formik.tsx Line 634 in c7d4114
|
The solution should be to use setFieldValue and setFieldTouched which let you override validation. So you should be able to write: const Component = ({ field, form, ...rest }) => {
const onBlur = e => {
e.target.value = "Blurred Value";
form.setFieldValue(field.name, "Blurred Value", true /* force validation */);
form.setFieldTouched(field.name, true, false /* force abort validation */);
};
return (
<input
style={{ border: "2px solid red" }}
{...field}
onBlur={onBlur}
{...rest}
/>
);
}; However, because https://github.com/jaredpalmer/formik/blob/master/packages/formik/src/Formik.tsx#L545 The current workaround would be to keep validateOnChange to true, and then override both onChange and onBlur in your component using setFieldValue (disabling validation in onChange, but keeping it in the onBlur). Not great tbh. I think a solution IMHO is to alter the Yet again, not having 2nd argument callback to setState (ie. the old inline cDU) is by far the most annoying parts of hooks. It's the cause of so much pain. It would be so much nicer if setXXXXX resolved after the update or had a callback that would run after the commit, but unfortunately this isn't possible with hooks. |
Thanks for the reply @jaredpalmer
I don't think that will work for the example that I gave where Changing it so // before
return validateOnChange && shouldValidate
? validateFormWithLowPriority(setIn(state.values, field, value))
: Promise.resolve(); // after
const willValidate = shouldValidate === undefined ? validateOnChange : shouldValidate;
return willValidate
? validateFormWithLowPriority(setIn(state.values, field, value))
: Promise.resolve(); Regarding the |
🐛 Bug report
Current Behavior
I have a complex component that reformats the user input when they blur the component. When using
<Field component={Component}/>
the validation runs on the previous value.Expected behavior
Validation should run on the state after the
onBlur
.Reproducible example
https://codesandbox.io/s/formik-codesandbox-template-1ewgq
Suggested solution(s)
N/A
Additional context
Related #2083, #1977, #2025
Your environment
The text was updated successfully, but these errors were encountered: