khanya-secure-validator
v1.0.0
Published
Simple and secure JSON payload and input validator for Node.js projects.
Downloads
6
Maintainers
Readme
khanya-secure-validator
Advanced JSON payload and input validator for Node.js projects.
Supports required fields, type checking, regex patterns, nested objects, optional fields, and default values.
Ideal for APIs, fintech applications, or any Node.js project where input validation is critical.
Features
- ✅ Required fields validation
- ✅ Type checking (
string,number,boolean,array,object) - ✅ Nested object validation
- ✅ Regex pattern validation
- ✅ Optional fields with default values
- ✅ Lightweight and zero dependencies
Installation
Using npm
npm install khanya-secure-validator
yarn add khanya-secure-validator
### CODE EXAMPLES
import { validate } from "khanya-secure-validator";
// Example payload
const payload = {
name: "Khanya",
age: 20,
email: "[email protected]",
address: { street: "123 Main St", city: "Mbabane" },
tags: ["nodejs", "validator"]
};
// Validation schema
const schema = {
name: { type: "string", required: true },
age: { type: "number", required: true },
email: { type: "string", required: true, regex: /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/ },
address: {
type: "object",
required: true,
nested: {
street: { type: "string", required: true },
city: { type: "string", required: true },
zip: { type: "string", required: false, default: "0000" }
}
},
tags: { type: "array", required: false }
};
// Run validation
const result = validate(payload, schema);
console.log(result);
/*
Output:
{
valid: true,
errors: []
}
*/
// Example with missing/wrong fields
const badPayload = { name: "Khanya", age: "20" };
const badResult = validate(badPayload, schema);
console.log(badResult);
/*
Output:
{
valid: false,
errors: [
'age should be of type number',
'email is required',
'address is required'
]
}
*/
#### API Reference
{
valid: boolean,
errors: string[]
}
### Schema Format
const schema = {
username: { type: "string", required: true },
password: { type: "string", required: true, regex: /^.{8,}$/ }, // at least 8 chars
profile: {
type: "object",
required: true,
nested: {
age: { type: "number", required: false, default: 18 },
email: { type: "string", regex: /^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/ }
}
}
};
