【发布时间】:2019-05-29 22:47:55
【问题描述】:
我有一个使用 reactjs + formik + yup 的表单。我有一个多文件上传字段。我想使用 yup 验证文件格式和最大大小。我该怎么做?
【问题讨论】:
我有一个使用 reactjs + formik + yup 的表单。我有一个多文件上传字段。我想使用 yup 验证文件格式和最大大小。我该怎么做?
【问题讨论】:
扩展 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
}
【讨论】:
此代码将用于验证图像格式。
const SUPPORTED_FORMATS = ["image/jpg", "image/jpeg", "image/gif", "image/png"];
export const validateImageType = (value) => {
if(value) {
let type = value.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)[0]
return SUPPORTED_FORMATS.includes(type)
}
}
Yup.mixed() .test('fileSize', "File is too large", value => value.size <= FILE_SIZE) .test('fileType', "Your Error Message", value => SUPPORTED_FORMATS.includes(value.type) )
【讨论】:
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 上)
【讨论】:
FileList。要检查required 要求,您需要白化您自己的验证器功能。这是实现了这种验证的文件的link。
const SUPPORTED_FORMATS = ['image/jpg', 'image/jpeg', 'image/png'];
const registerSchema = Yup.object().shape({
uriImage: Yup.mixed()
.nullable()
.required('A file is required')
.test('Fichier taille',
'upload file', (value) => !value || (value && value.size <= 1024 * 1024))
.test('format',
'upload file', (value) => !value || (value && SUPPORTED_FORMATS.includes(value.type))),
});
【讨论】: