Skip to content

Commit

Permalink
Prevent invalid files in online validator file selection
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mint-thompson committed Jul 31, 2024
1 parent 60ef1e3 commit e91db6a
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/components/FileInput.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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}`)]
Expand All @@ -73,22 +73,24 @@ export const FileInput = ({
e.preventDefault()
e.stopPropagation()
}
return allFilesAllowed
}
}

// Event handlers
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 (
Expand Down

0 comments on commit e91db6a

Please sign in to comment.