I have an array of objects which I receive from the input tag. I want to compare a particular value in the object whether it matches to the array or not. For example the input takes in multiple files, but i need it to be only of particular formats. The format is of either png or jpeg. The below show correct when i am uploading only one file, I want it to work when uploading multiple files at once.
I want to verify whether the whole object contains valid formats, if all the files are of valid format, then the files will be uploaded, and if one of the file format doesn't match, then files will not be uploaded.
Thank you in advance.
target.files gives enter image description here
const IMAGE_TYPES = ['image/png', 'image/jpeg'];
const handleClick = ({target}) => {
Object.keys(target.files).forEach((key) => {
if (IMAGE_TYPES.includes(target.files[key].type)) {
setIsInvalidImageFormat(false);
} else {
setIsInvalidImageFormat(true);
}
});
};
<input
id='icon-button-photo'
multiple
onChange={handleClick}
type='file'
/>
Array.prototype.every
as well as Array.prototype.some
are the tools for any boolean based validation of array entries. It also might be easier / better readable to make use of Object.values
instead of Object.keys
...
function setIsInvalidImageFormat(isAllValid) {
console.log({ isAllValid });
}
const IMAGE_TYPES = ['image/png', 'image/jpeg'];
function handleClick({ target }) {
setIsInvalidImageFormat(
Object
.values(target.files)
.every(fileData =>
IMAGE_TYPES.includes(fileData.type)
)
);
};
.as-console-wrapper { bottom: 0; }
<input
id="icon-button-photo"
multiple
onChange="handleClick(event)"
type='file'
/>
<!--
<input
id='icon-button-photo'
multiple
onChange={handleClick}
type='file'
/>
//-->