After submitting a form and getting async error responses I want them to be visible on the form.
My inputs show an error when form.errors[field.name] && form.touched[field.name];
So I try to both set errors and touch the related fields.
So far I've tried:
setErrors(errors)
setTouched(touched)
as well as looping through all errors and calling
setFieldError(key, name)
setFieldTouched(key, true);
In either case, whatever I call second works and the first doesn't.
it looks like setErrors overwrites touched and vice versa.
I also tried setStatus({ errors, touched }), but that didn't seem to work at all, but maybe I'm using the API wrong here.
Can you upgrade to 11 and report back.
Ran into the same issue today, even after upgrading to 0.11.5. The use case is pretty simple -- I'm running some custom validation against a secondary action in the form:
handlePublish = () => {
const { setFieldError, setFieldTouched, values } = this.props;
let valid = true;
if (!values.title) {
setFieldTouched('title', true);
setFieldError('title', 'Title is required to publish');
valid = false;
}
// ... if valid do the thing...
}
Found that this workaround produces the expected results:
if (!values.title) {
setFieldTouched('title', true);
window.setTimeout(() => { setFieldError('title', 'Title is required to publish'); }, 100);
}
But that this doesn't:
if (!values.title) {
setFieldError('title', 'Title is required to publish');
window.setTimeout(() => { setFieldTouched('title', true); }, 100);
}
setFieldTouched will rerun your validations, unless you've set validateOnBlur to false...which are overwriting your call to setFieldError.
Now that you can call validate, I am going to add a third argument to all the setters that lets you prevent calling validation. This will further prevent confusion.
See latest version of formik
I am going to add a third argument to all the setters that lets you prevent calling validation. This will further prevent confusion.
this will be great. Especially for setTouched.
I have an issue with my multistep form. I setTouched half of fields, than run validation, but because setTouched also do validation, i get isCancelled: true...
I have same issue with setTouched and setError but it's about useField. How can I get around this problem without setting validateOnBlur to false?
Most helpful comment
See latest version of formik