nextgen-validator
v1.0.2
Published
A lightweight and developer-friendly schema validation library for Node.js
Maintainers
Readme
nextgen-validator
A lightweight and developer-friendly schema validation library for Node.js with zero external dependencies.
Features
- 🚀 Simple syntax - Easy to read and write validation rules
- 📦 Zero dependencies - No external packages required
- 🔧 Framework agnostic - Works standalone or with Express/Fastify
- 📝 TypeScript support - Full TypeScript declarations included
- 🎯 Nested object support - Validate nested fields using dot notation
- 💬 Friendly error messages - Auto-generated, human-readable errors
Installation
npm install nextgen-validatorQuick Start
Method 1: Simple Result Object (Recommended)
const { validateSync } = require('nextgen-validator');
const schema = {
name: 'string|required|min:3',
age: 'number|required|min:18',
email: 'email|required',
active: 'boolean'
};
const data = {
name: 'John Doe',
age: 25,
email: '[email protected]',
active: true
};
const result = validateSync(schema, data);
if (!result.valid) {
console.log('Validation errors:', result.errors);
} else {
console.log('Data is valid!');
}Method 2: Throw on Error (Easiest)
const { validateAndThrow } = require('nextgen-validator');
try {
validateAndThrow(schema, data);
console.log('Data is valid!');
// Continue with your code...
} catch (error) {
console.log('Validation failed:', error.errors);
// error.errors contains array of error objects
}Method 3: Simple Boolean Check
const { isValid } = require('nextgen-validator');
if (isValid(schema, data)) {
console.log('Data is valid!');
} else {
const errors = validate(schema, data);
console.log('Validation errors:', errors);
}Method 4: Original Method (Manual Check)
const { validate } = require('nextgen-validator');
const errors = validate(schema, data);
if (errors.length > 0) {
console.log('Validation errors:', errors);
} else {
console.log('Data is valid!');
}Supported Data Types
string- String valuesnumber- Numeric valuesboolean- Boolean valuesarray- Array valuesobject- Plain objects (not arrays)email- Email addressesdate- Date objects, date strings, or timestamps
Supported Rules
required
Field must be present and not empty.
{ name: 'string|required' }min:<number>
Minimum value/length.
- For numbers: minimum numeric value
- For strings/arrays: minimum length
{ age: 'number|min:18' }
{ name: 'string|min:3' }
{ tags: 'array|min:2' }max:<number>
Maximum value/length.
- For numbers: maximum numeric value
- For strings/arrays: maximum length
{ age: 'number|max:100' }
{ name: 'string|max:50' }
{ tags: 'array|max:10' }length:<number>
Exact length (for strings and arrays).
{ code: 'string|length:5' }
{ items: 'array|length:3' }in:a,b,c
Allowed values (whitelist).
{ status: 'string|in:active,inactive,pending' }
{ priority: 'number|in:1,2,3' }Nested Objects
Use dot notation to validate nested object properties:
const schema = {
'profile.name': 'string|required',
'profile.age': 'number|min:18',
'user.profile.contact.email': 'email|required'
};
const data = {
profile: {
name: 'John Doe',
age: 25
},
user: {
profile: {
contact: {
email: '[email protected]'
}
}
}
};
const errors = validate(schema, data);Express Middleware
const express = require('express');
const { validateRequest } = require('nextgen-validator');
const app = express();
app.use(express.json());
const schema = {
name: 'string|required|min:3',
email: 'email|required'
};
app.post('/users', validateRequest(schema), (req, res) => {
// req.body is validated at this point
res.json({ success: true, data: req.body });
});
app.listen(3000);On validation failure, the middleware returns a 400 response with:
{
"success": false,
"errors": [
{
"field": "name",
"rule": "required",
"message": "Field 'name' is required"
}
]
}Fastify Middleware
const fastify = require('fastify');
const { validateRequest } = require('nextgen-validator');
const app = fastify();
const schema = {
name: 'string|required|min:3',
email: 'email|required'
};
app.post('/users', {
preHandler: validateRequest(schema, 'fastify')
}, async (request, reply) => {
// request.body is validated at this point
return { success: true, data: request.body };
});
app.listen(3000);Error Format
When validation fails, an array of error objects is returned:
[
{
field: 'name', // Field path (supports dot notation)
rule: 'required', // Rule that failed
message: 'Field \'name\' is required' // Human-readable message
},
{
field: 'age',
rule: 'min',
message: 'Field \'age\' must be at least 18'
}
]Examples
Complete Form Validation
const { validate } = require('nextgen-validator');
const schema = {
username: 'string|required|min:3|max:20',
email: 'email|required',
password: 'string|required|min:8',
age: 'number|required|min:18|max:120',
status: 'string|in:active,inactive',
tags: 'array|min:1|max:5',
profile: 'object'
};
const data = {
username: 'johndoe',
email: '[email protected]',
password: 'secret123',
age: 25,
status: 'active',
tags: ['developer', 'nodejs'],
profile: {
bio: 'Software developer'
}
};
const errors = validate(schema, data);Conditional Validation with Optional Fields
// Optional fields are skipped if undefined/null/empty
const schema = {
name: 'string|required',
email: 'email', // Optional - will only validate if present
phone: 'string|min:10' // Optional - will only validate if present
};
const data1 = { name: 'John' }; // Valid - email and phone are optional
const data2 = { name: 'John', email: 'invalid' }; // Invalid - email format wrongComplex Nested Validation
const schema = {
'user.name': 'string|required',
'user.email': 'email|required',
'user.address.street': 'string|required',
'user.address.city': 'string|required',
'user.address.zip': 'string|length:5',
'user.settings.theme': 'string|in:light,dark'
};
const data = {
user: {
name: 'John Doe',
email: '[email protected]',
address: {
street: '123 Main St',
city: 'New York',
zip: '10001'
},
settings: {
theme: 'dark'
}
}
};
const errors = validate(schema, data);API Reference
validate(schema, data)
Main validation function.
Parameters:
schema(Object): Validation schema objectdata(Object): Data to validate
Returns:
Array<ValidationError>: Array of validation errors (empty if valid)
Throws:
Error: If schema or data is invalid
validateSync(schema, data)
Validate and return result object with valid flag (Recommended for most cases).
Parameters:
schema(Object): Validation schema objectdata(Object): Data to validate
Returns:
Object:{ valid: boolean, errors: Array<ValidationError> }
Example:
const result = validateSync(schema, data);
if (!result.valid) {
// Handle errors
console.log(result.errors);
}validateAndThrow(schema, data)
Validate and throw error if validation fails (Easiest to use).
Parameters:
schema(Object): Validation schema objectdata(Object): Data to validate
Throws:
ValidationError: If validation fails (error.errors contains the errors array)
Example:
try {
validateAndThrow(schema, data);
// Data is valid, continue...
} catch (error) {
// error.errors contains validation errors
console.log(error.errors);
}isValid(schema, data)
Quick boolean check if data is valid.
Parameters:
schema(Object): Validation schema objectdata(Object): Data to validate
Returns:
boolean:trueif valid,falseotherwise
Example:
if (isValid(schema, data)) {
// Data is valid
} else {
// Data is invalid
}validateRequest(schema, framework?)
Creates middleware for Express or Fastify.
Parameters:
schema(Object): Validation schema objectframework(string, optional): 'express' or 'fastify'. Auto-detected if not provided.
Returns:
- Middleware function for the specified framework
TypeScript Support
TypeScript declarations are included:
import {
validate,
validateSync,
validateAndThrow,
isValid,
validateRequest,
ValidationError,
ValidationSchema
} from 'nextgen-validator';
const schema: ValidationSchema = {
name: 'string|required',
age: 'number|min:18'
};
const errors: ValidationError[] = validate(schema, data);Testing
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverageContributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT
Changelog
1.0.0
- Initial release
- Support for basic types and rules
- Express and Fastify middleware
- TypeScript declarations
- Comprehensive test coverage
