Html file input tag is given below which only accept .csv files.
<input id="csvFileInput" type="file" accept=".csv"/>
That works perfect. But my case is..
In the file chooser window, user can select 'all types' instead of '.csv file'. Then user can choose any file type. How could I handle that situation?
Can I handle that changing only Html tag? or another Javascript tactic to be implement?
Thanks, Best Regards..
The <input type="file"> defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files to be selected, add the multiple attribute. Tip: Always add the <label> tag for best accessibility practices!
You can add a validation onchange
an validation the file extension.
Though in html the input type accepts .png
but in js the regex is failing since it is designed to accepts only csv. You can modify the html to accept only csv
var regex = new RegExp("(.*?)\.(csv)$");
function triggerValidation(el) {
if (!(regex.test(el.value.toLowerCase()))) {
el.value = '';
alert('Please select correct file format');
}
}
<input id="csvFileInput" type="file" accept=".png" onchange='triggerValidation(this)'>
Whether you restrict the "accept=" using the extension or the mime type or both, the user can always switch to 'All files'.
For example,
var selectedFile = document.getElementById('csvFileInput');
selectedFile.onchange = function(e){
switch ((this.value.match(/\.([^\.]+)$/i)[1]).toLowerCase()) {
case 'csv':
case 'txt': /* since they might have a CSV saved as TXT */
/* ... insert action for valid file extension */
default:
/* Here notify user that this file extension is not suitable */
this.value=''; /* ... and erase the file */
}
};
Remember the user can always defeat the process by renaming (for example) an .exe to a .csv, so where relevant you should also check the content of the file to meet your criteria, on the server side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With