Can't set 'touched' to true
Asked Answered
D

3

9

I just trying to create a custom Formik <Field />. It is a <input type = file /> with opacity=0 and depending of values i styling my <Error /> component and <input type = text />. values.photo is ok. The problem is that touched never becoming true, so i can't show my <Error /> component. Can you explain what goes wrong? https://codesandbox.io/s/purple-violet-qgxr3?file=/src/components/FileInput.js

Demiurge answered 5/7, 2020 at 9:48 Comment(0)
M
17

in your file input component just add this:

form.setTouched({...form.touched,[field.name]: true });

setTouched take object of fields and field.name is the file input name.

Meissner answered 5/7, 2020 at 10:19 Comment(5)
It works not proper, i added one more input to show it. I faced this problem before. When i called setTouched it overwrite all 'touched' objectDemiurge
if you have multiple input just pass form.touched with the object and assign the field you want check edited aswer.Meissner
Ah, can you show some code please? I'm new in FormicDemiurge
I've tried to save object form.touched to local state and then to add to this object new property: [field.name]:true and pass it to setTouched. But it seems that in some moment form.touched became undefined and again i overwrite. It is so tricky for meDemiurge
what do you mean save form.touched in local state ? you can access it from props .Meissner
J
0

Formik provides a function called setFieldTouched which can be used to set the touched value for specific field manually

setFieldTouched: (field: string, isTouched?: boolean, shouldValidate?: boolean)
Joliejoliet answered 1/9 at 15:26 Comment(0)
D
-2

when you handle the file input by listening to onChange event. As soon as that onChange method is called you can mark your field asTouched by calling .markAsTouched() so that it would show the error if the condition in validated.

Diver answered 5/7, 2020 at 10:22 Comment(2)
Are you sure that .markAsTouched() is a Formik function? I cant find it in the documentation.Penitent
That's not part of FormikSpondylitis

© 2022 - 2024 — McMap. All rights reserved.