【问题标题】:How to validate Yup files uploads with typescript如何使用打字稿验证 Yup 文件上传
【发布时间】:2022-11-19 15:35:14
【问题描述】:

我需要我的 profileImgFile 被要求我想要我的 validationSchema 中的类型.目前验证按预期工作,但打字稿不喜欢 validationSchema。

错误本身:输入 'ObjectSchema<Assign<ObjectShape, { name: RequiredStringSchema<string |未定义,任何对象>;描述:RequiredStringSchema<string |未定义,任何对象>; profileImgFile: 混合架构<...>; }>, AnyObject, TypeOfShape<...>, AssertsShape<...>>' 不可分配给类型 'ObjectSchemaOf<IForm, never>'。

根据我在文档中阅读的内容,普遍共识是使用 yup mixed。另一种解决方案是使用 Yup.object() 但你必须处理文件属性。

profileImgFile: Yup.mixed().required("Required")

// Another possible solution
profileImgFile: Yup.object({
  // somehow spread all files Properties, or FileList properties.
}).required("Required")

无论如何,这是工作示例code-sandbox

interface IForm {
  name: string;
  description: string;
  profileImgFile: File;
}

 const validationSchema: Yup.SchemaOf<IForm> = Yup.object().shape({
    name: Yup.string().required("Required"),
    description: Yup.string().required("Required"),
    profileImgFile: Yup.mixed().required("Required")
  });


const {
    register,
    handleSubmit,
    control,
    reset,
    formState: { errors }
  } = useForm<IForm>({
    resolver: yupResolver(validationSchema)
  });

<Controller
   name="profileImgFile"
   control={control}
   render={({ field }) => (
    <input
    ref={fileInputRef}
     type="file"
     id="avatar"
     onChange={(val) => {
       field?.onChange(val?.target?.files);
     }}
     name="profileImgFile"
     accept="image/png, image/jpeg"
   />
  )}
/>

【问题讨论】:

    标签: javascript typescript react-hook-form yup


    【解决方案1】:

    如果我们从文件输入开始,它将与 FileList 实例绑定。

    <Form.Group
        controlId="profileImgFile">
        <Form.Control
            {...register("profileImgFile")}
            type="file"/>
        <Form.Control.Feedback type="invalid">{errors.profileImgFile?.message}</Form.Control.Feedback>
    </Form.Group>
    

    因此,profileImgFile 必须在IForm 中这样声明:

    interface IForm {
      name: string;
      description: string;
      profileImgFile: FileList;
    }
    

    在测试了许多其他方法之后,我在我的应用程序中采用了 Yup.mixed().test() 方法,如下所示。您可以使用其他文件检查(文件大小等)扩展 .test() 链。

    const validationSchema: Yup.SchemaOf<IForm> = Yup.object().shape({
        name: Yup.string().required("Required"),
        description: Yup.string().required("Required"),
        profileImgFile: Yup.mixed().test(
            "required", 
            "Please select a file", 
            (files: FileList) => files?.length > 0)
    });
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2021-05-16
      • 1970-01-01
      • 2019-09-29
      • 2019-07-11
      • 2019-10-05
      • 2022-12-19
      • 2018-05-18
      • 2019-05-29
      相关资源
      最近更新 更多