Home >Web Front-end >JS Tutorial >File type validation when uploading using JavaScript
Employment-only social media platforms allow users to create accounts and will be asked to upload necessary documents so they can be analyzed by recruiters. In order to collect files from users, these websites will provide "Upload file" or "Select file" option in their user details form; they only accept specific file types such as ".pdf", ".jpg", ".png" "wait. This process is called file verification and can be done using JavaScript.
In this article, we will design an option to validate file types using JavaScript. To do this, here's how -
Step 1 - Create a function called validateFileType().
Step 2 - When the file input field value changes, trigger the validateFileType() function.
Step 3 - Use document.getElementById('fileInput').files[0] to retrieve the selected file from the file input field.
Step 4 - Define an array called allowedTypes that contains the allowed file types (e.g. "image/jpeg", "image/png", "application/pdf") .
Step 5 - Use the includes() method to check whether the type of the selected file is included in the allowedTypes array.
If in the allowedTypes array, display the file name on the screen.
If the file type is not found, follow the steps below.
Step 6 - Display a warning message to the user stating "Invalid file type. Please select a JPEG, PNG, or PDF file."
Step 7 - Clear the name of the file input field by setting document.getElementById('fileInput').value to the empty string.
In the example below we try to validate the file type when uploading using the above method -
<!DOCTYPE html> <html> <head> <title>File Type Validation Example</title> <script> function validateFileType() { var selectedFile = document.getElementById('fileInput').files[0]; var allowedTypes = ['image/jpeg', 'image/png', 'application/pdf']; if (!allowedTypes.includes(selectedFile.type)) { alert('Invalid file type. Please upload a JPEG, PNG, or PDF file.'); document.getElementById('fileInput').value = ''; } } </script> </head> <body> <h1>File Type Validation Example</h1> <input type="file" id="fileInput" onchange="validateFileType()"> </body> </html>
After executing the above procedure, try to upload the file. If the file is ".jpg", ".png" or ".pdf", the file name will be displayed on the screen. Otherwise, it will display a warning stating "Invalid file type".
The above is the detailed content of File type validation when uploading using JavaScript. For more information, please follow other related articles on the PHP Chinese website!