npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

nextgen-validator

v1.0.2

Published

A lightweight and developer-friendly schema validation library for Node.js

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-validator

Quick 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 values
  • number - Numeric values
  • boolean - Boolean values
  • array - Array values
  • object - Plain objects (not arrays)
  • email - Email addresses
  • date - 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 wrong

Complex 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 object
  • data (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 object
  • data (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 object
  • data (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 object
  • data (Object): Data to validate

Returns:

  • boolean: true if valid, false otherwise

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 object
  • framework (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:coverage

Contributing

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