From e91db6a69ad5273ea9ed2de259c861d10827df97 Mon Sep 17 00:00:00 2001 From: Mint Thompson Date: Wed, 31 Jul 2024 14:49:32 -0400 Subject: [PATCH] Prevent invalid files in online validator file selection A file may be submitted to the online validator by drag-and-drop or by using a file selection window. In both cases, prevent the submission of files that are not one of the accepted types, and show an error when the file is not one of the accepted types. --- src/components/FileInput.jsx | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/components/FileInput.jsx b/src/components/FileInput.jsx index 99764fb..d426f4b 100644 --- a/src/components/FileInput.jsx +++ b/src/components/FileInput.jsx @@ -54,8 +54,8 @@ export const FileInput = ({ if (accept) { const acceptedTypes = accept.split(",") let allFilesAllowed = true - for (let i = 0; i < e.dataTransfer.files.length; i += 1) { - const file = e.dataTransfer.files[parseInt(`${i}`)] + for (let i = 0; i < e.target.files.length; i += 1) { + const file = e.target.files[parseInt(`${i}`)] if (allFilesAllowed) { for (let j = 0; j < acceptedTypes.length; j += 1) { const fileType = acceptedTypes[parseInt(`${j}`)] @@ -73,6 +73,7 @@ export const FileInput = ({ e.preventDefault() e.stopPropagation() } + return allFilesAllowed } } @@ -80,15 +81,16 @@ export const FileInput = ({ const handleDragOver = () => setIsDragging(true) const handleDragLeave = () => setIsDragging(false) const handleDrop = (e) => { - preventInvalidFiles(e) setIsDragging(false) if (onDrop) onDrop(e) } const handleChange = (e) => { - setShowError(false) - setFile(e.target.files.length > 0 ? e.target.files[0] : null) - if (onChange) onChange(e) + const allFilesAllowed = preventInvalidFiles(e) + if (allFilesAllowed) { + setFile(e.target.files.length > 0 ? e.target.files[0] : null) + if (onChange) onChange(e) + } } return (