3

I'm developing a web app that lets you import into a database from a CSV file. I'd like to include some validations on the frontend so make sure that only valid csv files are sent to the server for import.

I'm using a React front end and I'm currently doing the validation in an onDrop event:

onDrop = (file) => {
  const { showNotification } = this.props;
  if (file[0].type !== 'text/csv') {
    showNotification('Sorry, thats not a valid CSV file', 'warning');
  }else{
    this.setState({ file });
  }
}

This works fine on my Mac, but if you try it on a Windows machine, a CSV has a file type of application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. I've come to learn that there are a whole bunch of file types similar to this one, so I don't think checking a file's type is the best way to validate anymore.

An alternate method I'm trying is to parse it on the client side, and if it can be parsed, then the validation passes (the CSV's I'm dealing with aren't particularly large). However, the parsing happens asynchronously, so the validation passes before the file has been parsed:

onDrop = (file) => {
  let csv;
  Papa.parse(file[0], {
    complete: function(results){
      csv = results;
    }
  });
  const { showNotification } = this.props;
  if (csv) {
    showNotification('Sorry, thats not a valid CSV file', 'warning');
  }else{
    this.setState({ file });
  }
}

Any suggestions on a good way to validate a CSV file that does not involve checking the file type? Any suggestions for doing it via parsing and managing the asynchronous behavior?

quicklikerabbit
  • 2,040
  • 4
  • 21
  • 34
  • You're mistaken, a CSV file has a type of `text/csv` on any OS, however an `xlsx` file would have the type you've encountered, as it clearly a file type that comes from Office. At the end of the day, your clientside validation is meaningless, other than maybe for showing a message to users, you'll still need to verify the file type on the server. – adeneo Aug 11 '17 at 21:20
  • I'm not sure that's true, because I've done the import with the same file on two machines and I get the result described above. Regardless, I'm asking how to validate on the client side to provide feedback to the user; it's not a replacement for server side validation. – quicklikerabbit Aug 11 '17 at 21:23
  • I guess you'd need a list of all file types you accept then, here's the [Office ones](https://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc), and here's [MDN's list](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types) – adeneo Aug 11 '17 at 21:32

0 Answers0