我正在使用 react-hook-form 處理一個簡單的檔案上傳表單,我需要驗證是否已選擇檔案進行上傳。使用 yup 進行驗證。我意識到關于這個主題還有其他問題,但我無法找到可行的解決方案。
我的檔案上傳組件基于(幾乎 100% 相同)這個答案https://stackoverflow.com/a/68519175/1769106。它似乎作業得很好,如果我禁用驗證檔案已正確上傳。
我面臨的問題是在驗證是否已選擇檔案時出現錯誤file must be a 'object' type, but the final value was: 'null'。
這是一個顯示問題的CodeSandbox。我添加了一些列印顯示“檔案”表單屬性的內容及其型別(顯示為物件)
uj5u.com熱心網友回復:
使用下面的模式驗證,它應該按預期作業。
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;
})
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/428959.html
