Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept csv files only via a Html file input

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..

like image 264
Asaprab Avatar asked May 18 '17 04:05

Asaprab


People also ask

How do you input a file in HTML?

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!


2 Answers

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)'>
like image 57
brk Avatar answered Oct 21 '22 15:10

brk


HTML will always allow user to click 'All files'

Whether you restrict the "accept=" using the extension or the mime type or both, the user can always switch to 'All files'.

Javascript is needed

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 */
    }
};

Server side validation is also needed

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.

like image 30
Eureka Avatar answered Oct 21 '22 14:10

Eureka