gpt4 book ai didi

reactjs - Formik 和 yup 验证正在验证一个非必需的文件输入字段

转载 作者:行者123 更新时间:2023-12-05 03:46:26 25 4
gpt4 key购买 nike

我有一个输入字段(类型文件),出于某种原因即使不是必需的也可以验证。有了序列号,我有一个验证,它不是必需的,似乎工作正常,提交空字段时没有错误。对于文件输入字段,我只希望输入字段在上传文件时进行验证。我做错了什么?,当我点击提交测试验证时,我得到了这个(见下图)。

这是我的代码:

const validationSchema = Yup.object({
title: Yup.string()
.required("Title is required")
.min(8, "Title must be at least 8 characters")
.max(100, "Title cannot be more than 100 characters"),
description: Yup.string()
.required("Description is required")
.min(8, "Description must be at least 8 characters")
.max(100, "Description cannot be more than 100 characters"),
serialNumber: Yup.string()
.min(4, "Serial number must be at least 4 characters")
.max(16, "Serial number cannot be more than 16 characters"),
productStatus: Yup.number().required("A Status is required"),
productType: Yup.number().required("A type is required"),
img: Yup.mixed()
.test(
"fileSize",
"File size too large, max file size is 1 Mb",
(file) => file && file.size <= 1100000
)
.test(
"fileType",
"Incorrect file type",
(file) =>
file && ["image/png", "image/jpg", "image/jpeg"].includes(file.type)
),
});
{formik.errors["img"] && formik.touched["img"] && (
<div style={{ color: "#B2484D", fontSize: ".8rem" }}>
{formik.errors.img}
</div>
)}

<Field name="img">
{() => {
// < - this will take fieldProps.. not used in this case, using formik instead
return (
<>
<input
onBlur={formik.handleBlur}
onChange={({ currentTarget }) => {
const file = currentTarget.files![0];
const reader = new FileReader();

if (file) {
reader.onloadend = () => {
setSelectedFile({
file,
previewURI: reader.result!,
});

setuploadbtnLabel(
`You selected: ${file.name} - click again to change`
);
};
reader.readAsDataURL(file);
formik.setFieldValue("img", file);
}
}}
ref={inputFile}
type="file"
style={{ display: "none" }}
accept=".png,.jpg,.jpeg"
/>
</>
);
}}
</Field>

编辑:这是一个codesandbox https://codesandbox.io/s/thirsty-chandrasekhar-34q1q?file=/src/App.js

enter image description here

最佳答案

我认为您应该尝试将 notRequired() 甚至 nullable() 添加到 YUP 模式定义的 img 字段中。来自是的docs :

Mark the schema as not required. Passing undefined (or null for nullable schema) as value will not fail validation.

编辑:根据您提供的沙箱,我能够弄明白。问题来自您添加的测试。基本上,问题是当没有选择文件时 fileundefined,因此验证总是失败。

例如你可以改变这个:

 .test(
"fileSize",
"File size too large, max file size is 1 Mb",
(file) => file && file.size <= 1100000
)

对此:

.test(
"fileSize",
"File size too large, max file size is 1 Mb",
(file) => {
if (file) {
return file.size <= 1100000;
} else {
return true;
}
}
)

notRequired()nullable() 甚至都不是让它按照您期望的方式工作所必需的。这是 sandbox 的链接有了这个修复。如果这对您有用,请将答案标记为已接受。

祝你好运!

关于reactjs - Formik 和 yup 验证正在验证一个非必需的文件输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65297160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com