0
votes

I am using formik and Yup to handle by form data and Form Validation in react . I am trying to change the value of "Showfile" to true to do conditional validation But value is not changing.

                             

                                    
                                    TextField
                                    label="Resume"
                                    star="*"
                                    color="red"
                                    name="file"
                                    type="file"
                                    accept=".pdf ,.docx,.doc "
                                    onChange={(event) =>
                                        formik.setFieldValue(
                                            "file",
                                            event.currentTarget.files[0],
                                            "showfile",
                                            true
                                        )
                                    }
                                    value={formik.value}
                                />
                                
file: Yup.mixed().when("showfile", {
            is: true,
            then: Yup.mixed()
                .required("Required")
                .test(
                    "FILE_SIZE",
                    "Uploaded file is too big.",
                    (value) => value && value.size  value && SUPPORTED_FORMATS.includes(value.type)
                ),
Formik
            initialValues={{
                UserName: "",
                email: "",
                Phone: "",
                message: "",
                file: "",
                showfile: false,
                submit: false,
            }}
            validationSchema={validate}
            onSubmit={(values, actions) => {
                setTimeout(() => {
                    console.log(values);
                    actions.setSubmitting(false);
                }, 1000);
            }}
        >
1

1 Answers

0
votes

You are using setFieldValue wrong way. It only updates for one field. If you want set 2 filed, you need to call setFieldValue 2 times:

onChange={(event) => {
    formik.setFieldValue("file", event.currentTarget.files[0]);
    formik.setFieldValue("showfile", true);
}}

You can read more about setFieldValue in here: https://formik.org/docs/api/formik#setfieldvalue-field-string-value-any-shouldvalidate-boolean--void