If you want to implement different types of file with different extension then use the below code
function validateFile(file: File): boolean {
const allowedTypes: string[] = [‘image/jpeg’, ‘image/png’, ‘application/pdf’, ‘text/txt’];
const maxSize = 5 * 1024 * 1024; // Maximum file size (5MB)
<code> let isValidType = false;
for (const type of allowedTypes) {
if (file.type === type) {
isValidType = true;
break;
}
}
if (!isValidType) {
alert('Invalid file type. Only Text, JPEG, PNG, and PDF files are allowed.');
return false;
}
if (file.size > maxSize) {
alert('File size exceeds the maximum limit of 5MB.');
return false;
}
return true;
}
</code>
<code> let isValidType = false;
for (const type of allowedTypes) {
if (file.type === type) {
isValidType = true;
break;
}
}
if (!isValidType) {
alert('Invalid file type. Only Text, JPEG, PNG, and PDF files are allowed.');
return false;
}
if (file.size > maxSize) {
alert('File size exceeds the maximum limit of 5MB.');
return false;
}
return true;
}
</code>
let isValidType = false;
for (const type of allowedTypes) {
if (file.type === type) {
isValidType = true;
break;
}
}
if (!isValidType) {
alert('Invalid file type. Only Text, JPEG, PNG, and PDF files are allowed.');
return false;
}
if (file.size > maxSize) {
alert('File size exceeds the maximum limit of 5MB.');
return false;
}
return true;
}
New contributor
Ajay kumar Sinha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.