reactjs - Formik 和 yup 验证正在验证非必需的文件输入字段
问题描述
我有一个输入字段(类型文件),出于某种原因,即使不是必需的也会验证。使用序列号我有一个验证,它不是必需的,似乎工作正常,提交空字段时没有错误。对于文件输入字段,我只想在文件上传时验证输入字段。我在做什么错?,当我单击提交以测试验证时,我得到了这个(见下图)。
这是我的代码:
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>
编辑:这是一个代码框https://codesandbox.io/s/thirsty-chandrasekhar-34q1q?file=/src/App.js
解决方案
我认为您应该尝试添加notRequired()
甚至添加nullable()
到 img
YUP 模式定义上的字段。从是的文档:
将架构标记为不需要。将 undefined(或 null 用于可为空的模式)作为值传递不会使验证失败。
编辑:根据您提供的沙箱,我能够弄清楚。问题来自您添加的测试。基本上问题是当没有选择文件时未定义,因此验证总是file
失败。
例如你可以改变这个:
.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()
甚至没有必要让它按照您期望的方式工作。这是带有此修复程序的沙盒的链接。如果这对您有用,请将答案标记为已接受。
祝你好运!
推荐阅读
- c - 使用 C 代码连接到 Monetdb 时出现链接错误
- javascript - 基于不同数据属性的多级过滤DOM问题
- skype-for-business - Skype For Business Online UCWA 应用程序服务器在一段时间后停止工作
- python - 字符串集之间的差异不起作用
- java - h如何打印来自 Axis 1.4 存根的 XML 请求和响应
- active-directory - 活动目录 lastLogonTimestamp - 将整数转换为日期
- regex - 我想将双引号之间的每个字符串修剪为 16 个字符
- debugging - Roku 调试?
- activerecord - Yii ActiveRecord 中的 beforeFind() 和缓存
- python-3.x - 预提交挂钩返回 tortoiseHg 中已检查标记文件的列表