【问题标题】:Yup image validation, only if image is uploaded是的图像验证,仅当图像被上传时
【发布时间】:2022-10-19 12:51:42
【问题描述】:

我正在尝试为特色图片编写验证。这个字段也可以为空,所以我希望这个字段被验证为图像,只有当图像被上传时。

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(),
        }),
    });

目前,其给出的错误为:Error: Cyclic dependency, node was:"featured_image"

【问题讨论】:

    标签: reactjs yup


    【解决方案1】:

    循环错误与您的必填或非必填字段无关,您需要将 'featured-image' 添加到依赖项列表中,试试这个:

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

    【讨论】:

      【解决方案2】:

      如果我们需要制作图像字段不是 必需的然后 :

       image: Yup.mixed()
        .test("type", "We only support jpeg and jpg format", function (value) {
           if(value=='undefined' || value)
             return value && (value.type === "image/jpg" || value.type === "image/jpeg");
           }
           else{
              return true
           }
        }),
      

      现在,如果我们需要制作图像字段必需的然后 :

      image: Yup.mixed()
        .test('required', "Please upload a Profile Photo", (value) => {
          return value != null
        })
        .test("type", "We only support jpeg and jpg format", function (value) {
          return value && (value.type === "image/jpg" || value.type === "image/jpeg");
        }),
      

      【讨论】:

        猜你喜欢
        • 2017-03-06
        • 2015-09-07
        • 2018-01-03
        • 1970-01-01
        • 2016-01-31
        • 2011-06-22
        • 2018-01-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多