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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sourceregistry/node-validator

v1.1.6

Published

A minimal, dependency-free TypeScript/JavaScript library for runtime validation.

Readme

@sourceregistry/node-validator

npm version License CI Codecov

A lightweight, dependency-free runtime validation library for TypeScript and JavaScript.

node-validator is designed for production use where you want a small validation core, explicit error reporting, and strong TypeScript inference without pulling in a large schema framework.

Features

  • Zero runtime dependencies
  • Path-aware validation errors for nested values
  • Composable primitives for strings, numbers, booleans, arrays, tuples, objects, records, unions, and custom refinements
  • safeParse() for result-based control flow and parse() for exception-based control flow
  • Type inference from validators, object schemas, tuples, transforms, and unions
  • Unknown-key handling for objects: strip, allow, or error
  • CI-ready package tooling with coverage thresholds and multi-version Node verification

Requirements

  • Node.js >=18

Installation

npm install @sourceregistry/node-validator

Validator is also exported as v for shorter schema definitions.

Quick Start

import { v } from "@sourceregistry/node-validator";

const userValidator = v.object({
  id: v.number({ integer: true, min: 1 }),
  name: v.string({ trim: true, non_empty: true, min: 2 }),
  email: v.optional(
    v.string({ pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ })
  ),
  roles: v.array(v.enum(["admin", "user"] as const), { min: 1 }),
});

const result = v.safeParse(userValidator, {
  id: 1,
  name: " Ada ",
  roles: ["admin"],
});

if (result.success) {
  console.log(result.data.name); // "Ada"
} else {
  console.error(result.errors);
}

Parse Modes

Use safeParse() when validation failures are part of normal control flow:

import { v } from "@sourceregistry/node-validator";

const result = v.safeParse(v.number({ min: 1 }), 0);

if (!result.success) {
  console.log(result.errors);
}

Use parse() when invalid input should fail fast:

import { SchemaValidationError, v } from "@sourceregistry/node-validator";

try {
  const port = v.parse(
    v.number({ integer: true, min: 1, max: 65535 }),
    3000
  );
  console.log(port);
} catch (error) {
  if (error instanceof SchemaValidationError) {
    console.error(error.errors);
  }
}

Use safeParseFormData() or parseFormData() when the payload starts as FormData:

const formData = new FormData();
formData.set("name", " Ada ");
formData.append("roles", "admin");
formData.append("roles", "user");

const result = v.safeParseFormData(
  v.object({
    name: v.string({ trim: true, non_empty: true }),
    roles: v.array(v.enum(["admin", "user"] as const), { min: 1 }),
  }),
  formData
);

Repeated FormData keys are exposed to validators as arrays in insertion order. Single entries remain single values.

Core Validators

Strings

const username = v.string({
  trim: true,
  non_empty: true,
  min: 3,
  max: 20,
  pattern: /^[a-z0-9_]+$/i,
});

Numbers

const quantity = v.number({
  integer: true,
  min: 0,
  max: 100,
});

Arrays and Tuples

const tags = v.array(
  v.string({ trim: true, non_empty: true }),
  { max: 10 }
);

const point = v.tuple([
  v.number(),
  v.number(),
]);

Objects and Records

const config = v.object(
  {
    host: v.string({ non_empty: true }),
    port: v.number({ integer: true, min: 1, max: 65535 }),
  },
  { unknownKeys: "error" }
);

const envMap = v.record(v.string(), {
  key: v.string({ pattern: /^[A-Z_]+$/ }),
});

Optional, Nullable, and Defaults

const nickname = v.optional(v.string());
const archivedAt = v.nullable(v.string());
const retries = v.withDefault(
  v.number({ integer: true, min: 0 }),
  3
);

Literals, Enums, Unions, Transforms, and Refinements

const mode = v.enum(["development", "production"] as const);

const id = v.union(
  v.number({ integer: true, min: 1 }),
  v.string({ non_empty: true })
);

const normalizedEmail = v.transform(
  v.string({ trim: true, non_empty: true }),
  (value) => value.toLowerCase()
);

const evenNumber = v.refine(
  v.number({ integer: true }),
  (value) => value % 2 === 0,
  "Expected an even number",
  "not_even"
);

Error Shape

Validation failures return a normalized issue array:

type ValidationIssue = {
  path: string;
  message: string;
  code?: string;
};

Example:

{
  success: false,
  errors: [
    { path: "$.roles[1]", message: "Expected string enum value", code: "invalid_type" }
  ]
}

Paths are rooted at $ and include object keys and array indexes.

API

| Export | Description | | --- | --- | | v | Shorthand alias for Validator. | | Validator.string(options?) | Validate strings with trimming, length, and regex options. | | Validator.number(options?) | Validate numbers with min, max, integer, and finite checks. | | Validator.boolean() | Validate boolean values. | | Validator.literal(value) | Validate one exact literal value. | | Validator.enum(values) | Validate one value from a string literal set. | | Validator.optional(inner) | Allow undefined. | | Validator.nullable(inner) | Allow null. | | Validator.withDefault(inner, fallback) | Apply a fallback when the input is undefined. | | Validator.array(inner, options?) | Validate arrays and their items. | | Validator.tuple(shape) | Validate a fixed-length tuple. | | Validator.object(shape, options?) | Validate plain objects using a validator shape. | | Validator.record(valueValidator, options?) | Validate object records and optionally validate keys. | | Validator.union(...validators) | Validate against the first matching validator. | | Validator.transform(base, mapper, message?, code?) | Map validated input into a new output type. | | Validator.refine(base, predicate, message, code?) | Add a custom predicate to an existing validator. | | Validator.safeParse(validator, value) | Return { success, data | errors }. | | Validator.safeParseFormData(validator, value) | Convert FormData to an object and return { success, data | errors }. | | Validator.parse(validator, value) | Return parsed data or throw SchemaValidationError. | | Validator.parseFormData(validator, value) | Convert FormData to an object and return parsed data or throw. | | ok(data) | Build a success result manually. | | fail(message, path, code?) | Build a failure result manually. | | runValidation(validator, value, path?) | Execute a validator directly. | | isFailure(result) | Type guard for failed validation results. |

Quality Gates

The package is verified with:

  • Type-checking via tsc
  • Runtime tests via vitest
  • Coverage thresholds set to 100%
  • Build verification for ESM, CJS, declarations, and sourcemaps
  • GitHub Actions CI on Node 18, 20, and 22

Development

npm run lint
npm test
npm run test:coverage
npm run build
npm run verify

Contributing

  • Add tests for new validators and behavior changes.
  • Preserve the error shape and parse semantics unless a breaking change is intended.
  • Keep lint, test:coverage, and build green before publishing.

Style Notes

  • Use unknownKeys for object unknown-key handling.
  • Use Validator.withDefault() for fallback values.
  • Validator.tuple() returns a mutable tuple type in TypeScript for easier downstream use.