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?