我有一个使用reactjs + formik + yup的表单。我有一个多文件上传字段。我想使用yup验证文件格式和最大大小。我该怎么办?
答案 0 :(得分:0)
只需自己处理即可-yup不能很好地验证我找到的文件。
类似的东西:
]]
答案 1 :(得分:0)
在Devin's answer上扩展,您可以使用yup进行验证。
const schema = Yup.object().shape({
files: Yup.array()
.nullable()
.required('VALIDATION_FIELD_REQUIRED')
.test('is-correct-file', 'VALIDATION_FIELD_FILE_BIG', checkIfFilesAreTooBig)
.test(
'is-big-file',
'VALIDATION_FIELD_FILE_WRONG_TYPE',
checkIfFilesAreCorrectType
),
})
其中的验证功能为:
export function checkIfFilesAreTooBig(files?: [File]): boolean {
let valid = true
if (files) {
files.map(file => {
const size = file.size / 1024 / 1024
if (size > 10) {
valid = false
}
})
}
return valid
}
export function checkIfFilesAreCorrectType(files?: [File]): boolean {
let valid = true
if (files) {
files.map(file => {
if (!['application/pdf', 'image/jpeg', 'image/png'].includes(file.type)) {
valid = false
}
})
}
return valid
}
答案 2 :(得分:0)
export const UploadFileSchema = yup.object().shape({
file: yup
.mixed()
.required("You need to provide a file")
.test("fileSize", "The file is too large", (value) => {
return value && value[0].sienter code hereze <= 2000000;
})
.test("type", "Only the following formats are accepted: .jpeg, .jpg, .bmp, .pdf and .doc", (value) => {
return value && (
value[0].type === "image/jpeg" ||
value[0].type === "image/bmp" ||
value[0].type === "image/png" ||
value[0].type === 'application/pdf' ||
value[0].type === "application/msword"
);
}),
});
此解决方案取自 Maksim Ivanov(在 youtube 上)