5

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

Asaprab
  • 148
  • 1
  • 15
  • 3
    You really need to validate that they've uploaded a valid file **server-side**, rather than client-side. What back-end technology are you using? – Obsidian Age May 18 '17 at 04:26
  • After selecting the file, you have to validate the file extension. This link may help you http://stackoverflow.com/questions/4234589/validation-of-file-extension-before-uploading-file – Aravinder May 18 '17 at 04:35
  • @Obsidian Age I'm using php as backend. But I need to validate on client side. – Asaprab May 18 '17 at 06:22
  • Thanks Aravinder.. – Asaprab May 18 '17 at 06:22

2 Answers2

4

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)'>
brk
  • 43,022
  • 4
  • 37
  • 61
1

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.

Eureka
  • 2,033
  • 10
  • 15
  • just a side note switch case always increase code complexity , object mapping is a better approach – brk May 18 '17 at 04:53
  • Thanks Eureka..Server side validation is a overwork I think..I managed it by only a simple JS validation. – Asaprab May 24 '17 at 09:15