Home > Mobile >  Yup image validation, only if image is uploaded
Yup image validation, only if image is uploaded

Time:03-19

I am trying to write a validation for featured image. This field could be nullable as well, so I want this field to be validate as image, only if image is uploaded.

const schema = Yup.object({
        featured_image: Yup.mixed().when("featured_image", {
            is: (value) => value?.length,
            then: (schema) =>
                schema
                    .test("name", "Image is required", (value) => {
                        return (
                            value != undefined &&
                            value[0] &&
                            value[0].name !== ""
                        );
                    })
                    .test("fileSize", "File must be less than 2MB", (value) => {
                        return (
                            value != undefined &&
                            value[0] &&
                            value[0].size <= 2000000
                        );
                    })
                    .test("type", "Only images are supported", (value) => {
                        return (
                            value != undefined &&
                            value[0] &&
                            value[0].type.includes("image")
                        );
                    }),
            otherwise: (schema) => schema.nullable(),
        }),
    });

Currently, its giving error as: Error: Cyclic dependency, node was:"featured_image"

CodePudding user response:

Cyclic error has nothing with your required or not required field, you need to add 'featured-image' to dependencies list, try this:

const validationSchema = yup.object().shape({
    //your scheme here
    },
     //cyclic dependencies
        [
            ['featured_image', 'featured_image'],
        ]
    )
  • Related