Reputation: 59
I'm using KnockoutJS in my MVc Project to load a csv file & provide a simple validation for import mechanism
The workflow is as follows:
this is an example of csv Lines :
Account_id,External_id,Amount,Transaction_Date,Office_date,Bank,Receipt_nbr,Type,statement,receipt,
0559394,,5,6/20/2017,7/7/2017,Cash,1729002903597,PNL,172900290,3597,
0099952,,19,6/20/2017,7/7/2017,Cash,1729002903653,PNL,172900290,3653,
,,,,,,,,,,
,,,,,,,,,,
,,,,,,,,,,
Here my code used to Upload file :
$('#lnkUpload').click(function () {
var FileToRead = document.getElementById('UserFile');
if (FileToRead.files.length > 0) {
var reader = new FileReader();
// assign function to the OnLoad event of the FileReader
// non synchronous event, therefore assign to other method
reader.onload = Load_CSVData;
// call the reader to capture the file
reader.readAsText(FileToRead.files.item(0));
}
self.userModel.removeAll();
});
function Load_CSVData(e) {
self.userModel.removeAll();
CSVLines = e.target.result.split(/\r\n|\n/);
$CSVLines = CSVLines.slice(1);
$.each($CSVLines, function (i, item) {
var element = item.split(","); // builds an array from comma delimited items
var LAccount_id = (element[0] == undefined) ? "" : element[0].trim();
var LExternal_id = (element[1] == undefined) ? "" : element[1].trim();
var LAmount = (element[2] == undefined) ? "" : element[2].trim();
var LTransaction_date = (element[3] == undefined) ? "" : element[3].trim();
var LOffice_date = (element[4] == undefined) ? "" : element[4].trim();
var LBank = (element[5] == undefined) ? "" : element[5].trim();
var LReceipt_nbr = (element[6] == undefined) ? "" : element[6].trim();
var LType = (element[7] == undefined) ? "" : element[7].trim();
var Lstatement = (element[8] == undefined) ? "" : element[8].trim();
var Lreceipt = (element[9] == undefined) ? "" : element[9].trim();
self.userModel.push(new userModel()
.Account_id(LAccount_id)
.External_id(LExternal_id)
.Amount(LAmount)
.Transaction_date(LTransaction_date)
.Office_date(LOffice_date)
.Bank(LBank)
.Receipt_nbr(LReceipt_nbr)
.Type(LType)
.statement(Lstatement)
.receipt(Lreceipt))
});
}
how can i update the code to Ignore and skip over empty Lines or treat them as the end of the input file or any other suggestion
Upvotes: 2
Views: 5695
Reputation: 2656
This will detect a line that consists only of commas and/or white space (so will match "\n", "", ",,,,,", ", , , , ," etc. but not ",,,,1,,,,,"
if (item.match(/^[,\s]*$/)) { continue; }
Upvotes: 1
Reputation: 425
You can detect if the current line is a newline character.
if(item == "\n") { continue; }
EDIT:
As matt pointed out, if the whitespace is made up of spaces the above solution will not work. Simply erase any spaces to detect if the row is made up of spaces.
if(item == "\n" || item.trim().length == 0) { continue; }
Upvotes: 5