The "Validator CSV" package is a powerful and easy-to-use tool for checking the integrity and quality of CSV files. With it, you can ensure that your CSV files are well formatted, meet header specifications, and meet your application's specific requirements.
You can install this package via npm. Make sure you have Node.js installed.
npm i validator-csv
To use validator-csv follow the examples:
Validating CSV through file path
const path = require("node:path");
const validator = require('validator-csv');
const Yup = require("yup");
const filePath = path.resolve(__dirname, "uploads", "clientes.csv");
const validationSchema = Yup.object().shape({
age: Yup.number().min(18, "Invalid age, the customer must be over 18 years old.").required("The field age is required."),
});
validator.validateCSV({
filePath,
headers: ["name", "age", "gender"],
schema: validationSchema,
}).then((data) => {
console.log(data);
}).catch((error) => {
console.error("Error:", error);
});
/*
data:{
headers: ["name","age","gender","erros"],
rows: [
["John Smith",18,"male",[]],
]
}
*/
Validating CSV through buffer
const fs = require("node:fs");
const path = require("node:path");
const validator = require('validator-csv');
const Yup = require("yup");
const filePath = path.join(__dirname, "uploads", "clientes.csv");
const csvBuffer = fs.readFileSync(filePath);
const validationSchema = Yup.object().shape({
age: Yup.number().min(18, "Invalid age, the customer must be over 18 years old.").required("The field age is required."),
});
validator
.validateCSVFromBuffer({
buffer: csvBuffer,
headers: ["name", "age", "gender"],
schema: validationSchema,
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error("Error:", error);
});
/*
data:{
headers: ["name","age","gender","erros"],
rows: [
["John Smith",18,"male",[]],
]
}
*/
By default, the separator parameter is set to a comma (","), but this setting can be modified by the user as needed.
Important Note About the Escape Character
When the text is encapsulated in double quotes ("), the separator will not impact the lines, thus ensuring the integrity of the data contained in the quotes.
ex:
validator.validateCSV({
filePath: filePath,
headers: ["name", "age", "gender"],
separator: ";",
schema: validationSchema,
}).then((data) => {
console.log(data);
});
Example of custom function with yup
const validationSchema = Yup.object().shape({
age: Yup.number().test("validate-age","Invalid age, the customer must be over 18 years old.",(element) => {
element >= 18
})
});
To view the examples, clone the Express repo and install the dependencies:
$ git clone --branch examples https://github.com/daviaquino87/validator-csv
$ cd validator-csv
$ npm install
$ npm run start
The original author of validator-csv is Davi Aquino.
MIT.