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

@flemminghansen/validator

v1.0.0

Published

Small flexible runtime validation tool for TypeScript and JavaScript

Readme

@flemminghansen/validator

npm version License: MIT

A lightweight, extensible validation library for Node.js and the browser.


Table of Contents


Introduction

Welcome to @flemminghansen/validator!
This library makes it a breeze to validate data during runtime with a simple API. It is an alternative to larger libraries like Zod or Yup, which can be an investment to learn. This library is far smaller and more flexible. 🚀


Installation

Install via npm:

npm install @flemminghansen/validator

Or using yarn:

yarn add @flemminghansen/validator

Features

  • Easy to Use: Straightforward API to add built-in and custom validators.
  • Extensible: Create your own validators to handle any special validation logic.
  • Lightweight: No unnecessary bloat—just what you need.
  • Isomorphic: Works in both Node.js and browser environments.

Usage

Default Validators

This library comes with a few default validators:

  • string
  • optionalString
  • number
  • optionalNumber
  • boolean
  • optionalBoolean

Using them is as simple as:

Example

import {
    validate,
    string, 
    number, 
    optional
    string,
    type ISchema,
} from "@flemminghansen/validator";

interface SchemaData {
  name: string;
  age: number;
  location: {
    country: string;
    city: string;
  };
}

// The ISchema makes it easy to match the schema with your existing types!
const mySchema: ISchema<SchemaData> = {
  name: string(),
  age: number(),
  location: {
    country: string(),
    city: optional(string()),
  },
};

  const validData: SchemaData = {
    name: "John Doe",
    age: 30,
    location: {
      country: "France",
    },
  };

  const invalidData: SchemaData = {
    name: "Jane Doe",
    age: '30', // <-- Invalid type
    location: {
      country: "France",
      city: "Paris",
    },
  };

  const isJohnValid = validate(mySchema, validData, "John's data");
  const isJaneValid = validate(mySchema, invalidData, "Jane's data");
  console.log(isJohnValid); // true
  console.log(isJaneValid); // false - Errors logged to console.

Custom Validator

If you need more specific validators, you can also easily create your own, and use them in the schema:

Example

interface SchemaData {
  name: string;
  age?: number;
}

const customNumberValidator = ({ min, max }: { min: number; max: number }) => ({
  validate: (
    value: number | undefined,
    sourceData: SchemaData
  ): value is number | undefined => {
    if (sourceData.name === "John Doe") {
      // We force John's age to be 69 at runtime. His age is not optional.
      return value === 69;
    }

    // Otherwise it is an optional
    if (value === undefined) return true;

    return value >= min && value <= max;
  },
});

const mySchema: ISchema<SchemaData> = {
  name: string(),
  age: customNumberValidator({ min: 0, max: 100 }),
};

const johnData: SchemaData = {
  name: "John Doe",
  age: 30,
};

const janeData: SchemaData = {
  name: "Jane Doe",
  age: 30,
};

const bobData: SchemaData = {
  name: "Bob Doe",
  age: -1,
};

const isJohnValid = validate(mySchema, johnData, "John's data");
const isJaneValid = validate(mySchema, janeData, "Jane's data");
const isBobValid = validate(mySchema, bobData, "Bob's data");
console.log(isJohnValid); // false
console.log(isJaneValid); // true
console.log(isBobValid); // false

Optional validator options

The optional validator accepts all falsy data except zero as true. Meaning, if you pass undefined, null or NaN, validators wrapped in the optional validator will pass.

However, if you need a more strict validation, you can pass an options object as a second parameter. If your value otherwise is falsy, the value is passed to the passed validator

Optional options: IOptionalOptions = {}

  • disallowNull?: boolean;
  • disallowNaN?: boolean;

Example

const schemaDefaultOptions: ISchema<IOptionsData> = {
  age: optional(number()),
};

console.log(validate(schemaDefaultOptions, { age: 0 }, "age zero")); // true
console.log(
  validate(schemaDefaultOptions, { age: undefined }, "age undefined")
); // true
console.log(validate(schemaDefaultOptions, { age: null }, "age null")); // true
console.log(validate(schemaDefaultOptions, { age: NaN }, "age NaN")); // true

const schemaWithOptions: ISchema<IOptionsData> = {
  age: optional(number(), {
    disallowNaN: true,
    disallowNull: true,
  }),
};

console.log(validate(schemaWithOptions, { age: 0 }, "age zero")); // true
console.log(validate(schemaWithOptions, { age: undefined }, "age undefined")); // true
console.log(validate(schemaWithOptions, { age: null }, "age null")); // false
console.log(validate(schemaWithOptions, { age: NaN }, "age NaN")); // false

More complex data types

Let's look at a more complex example, and look at some of the caveats and possibilities.

dynamicKeyObject

In the example below, note that the Customers does not have an explicit key = Record<string, Customer>. In order to overcome this issue, we use the dynamicKeyObject function in the schema, and passes the Customer type as a generic to keep type safety.

Caveat on array of objects.

The customer's orderhistory is any array of objects. Note that this returns as valid even if the array is empty. If a more strict validation is needed, you can create a custom validator.

Example

interface Customer {
  info: {
    username: string;
    imageUrl?: string;
  };
  orderHistory?: {
    orderId: string;
    orderDate: string;
  }[];
}

interface ComplexSchemaData {
  storeId: string;
  customers: Record<string, Customer>;
}

const complexSchema: ISchema<ComplexSchemaData> = {
  storeId: string(),
  customers: dynamicKeyObject<Customer>({
    info: {
      username: string(),
      imageUrl: optional(string()),
    },

    orderHistory: optional([
      {
        orderId: string(),
        orderDate: string(),
      },
    ]),
  }),
};

const complexData: ComplexSchemaData = {
  storeId: "123",
  customers: {
    customer1: {
      info: {
        username: "JohnDoe",
        imageUrl: "/images/image.jpg",
      },
      orderHistory: [
        {
          orderId: "789",
          orderDate: "2024-10-01",
        },
      ],
    },
    customer2: {
      info: {
        username: "JaneDoe",
      },
      orderHistory: [],
    },
    customer3: {
      info: {
        username: "BobDoe",
      },
    },
  },
};

console.log("complexData", validate(complexSchema, complexData, "complexData")); // true

Contributing

We welcome contributions!
Feel free to fork the repository, create issues, and submit pull requests.

  1. Fork the repository.
  2. Create your feature branch: git checkout -b my-feature
  3. Commit your changes: git commit -am 'Add new feature'
  4. Push to the branch: git push origin my-feature
  5. Create a new Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.


Happy validating! ✨