use*_*106 7 reactjs yup react-hook-form
我正在使用react-hook-form制作一个简单的文件上传表单,我需要验证是否已选择上传文件。使用 yup 进行验证。我意识到关于这个主题还有其他问题,但我无法找到可行的解决方案。
我的文件上传组件基于(几乎100%相同)这个答案/sf/answers/4796342281/。它似乎工作得很好,如果我禁用验证,文件就会正确上传。
我面临的问题是在验证是否已选择文件时出现错误file must be a 'object' type, but the final value was: 'null'。
这是显示问题的CodeSandbox 。我添加了一些打印内容,显示“文件”表单属性的内容及其类型(显示为对象)
Nem*_*nja 12
使用下面的模式验证,它应该按预期工作。
const fileFormSchema = yup.object().shape({
file: mixed()
.test("required", "You need to provide a file", (file) => {
// return file && file.size <-- u can use this if you don't want to allow empty files to be uploaded;
if (file) return true;
return false;
})
.test("fileSize", "The file is too large", (file) => {
//if u want to allow only certain file sizes
return file && file.size <= 2000000;
})
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10265 次 |
| 最近记录: |