validate-and-sanitize
v1.0.6
Published
A lightweight utility for validating and sanitizing user input. π
Maintainers
Readme
validate-and-sanitize
A lightweight utility for validating and sanitizing user input. π
π₯ Features
β
Validate required fields
β
Type-checking (string, number, etc.)
β
Remove SQL injection patterns
β
Trim spaces from string inputs
β
Option to sanitize all fields
π¦ Installation
Install via npm:
npm install validate-and-sanitizeπ’ Supports Both ESM and CommonJS
This library works with both ES Modules (ESM) and CommonJS (CJS).
β How to Import
For ES Modules (ECMAScript)
If your project uses ES modules ("type": "module" in package.json)
π Usage
Basic Example
import { validateAndSanitize } from "validate-and-sanitize";
// OR
// const { validateAndSanitize } = require("validate-and-sanitize");
const schema = {
username: { required: true, type: "string", label: "Username" },
email: { required: true, type: "string", label: "Email" },
age: { type: "number", label: "Age" },
};
const inputData = {
username: " JohnDoe ",
email: "[email protected]",
age: "25", // β Incorrect type
};
const result = validateAndSanitize(inputData, schema);
console.log(result);
/*
Output:
{
errors: ["Age must be of type number"]
}
*/Example with Sanitization
const inputData = {
username: " JohnDoe ",
email: "[email protected]",
bio: "Hello world! DROP TABLE users;", // β Contains SQL keywords
};
const result = validateAndSanitize(inputData, schema, true);
console.log(result);
/*
Output:
{
sanitizedData: {
username: "JohnDoe",
email: "[email protected]",
bio: "Hello world! " // SQL keywords removed
}
}
*/π API Reference
validateAndSanitize(data, schema, sanitizeAll = false)
Parameters:
data(Object) β User input dataschema(Object) β Validation schemasanitizeAll(Boolean) β Iftrue, all fields will be sanitized, including those not defined in the schema. Iffalse, only fields defined in the schema will be sanitized. (default:false)
Returns:
{ errors: string[] }if validation fails{ sanitizedData: Object }if successful
