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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@stackup/validate

v0.4.1

Published

Functional, tree-shakeable, schema validation

Downloads

5

Readme

Build Size Version License

A functional schema validation library.

  • Lightweight - My data validation library shouldn't be bigger than React.
  • Tree-shakeable - I don't want to take a hit for functionality that I'm not using.
  • Composable - I want to validate my data with tiny, single-purpose functions.
  • Type-safe - I want my validations to enforce my TypeScript types.

Table of Contents

Example

import { schema, assert, isString, isBlank, isNumber } from "@stackup/validate";

const userSchema = schema({
  name: assert(isString).then(refute(isBlank, "Can't be blank")),
  age: assert(isNumber).then(assert(age => age >= 18, "Must be 18 or older"))
});

const result = await userSchema.validate(data);

if (result.valid) {
  console.log(result.value);
} else {
  console.log(result.errors);
}

Installation

Install the package from NPM:

$ yarn add @stackup/validate

Operators

An operator is a function that returns a new Validator. You can chain together multiple operators with then:

assert(isString)
  .then(refute(isBlank))
  .then(map(value => value.trim()))
  .validate("hello!")
  .then(result => {
    if (result.valid) {
      console.log(result.value);
    } else {
      console.log(result.errors);
    }
  });

schema(shape)

Describes an object's properties.

schema({
  name: assert(isString),
  age: assert(isNumber)
});

assert(predicate, message?, path?)

Produces an error if a condition is not met.

assert(isString, "must be a string");

refute(predicate, message?, path?)

Produces an error if a condition is met.

refute(isBlank, "can't be blank");

map(transform)

Transforms the current value to a new value.

map(value => value.trim());

optional(validator)

Runs the given validator unless the value is undefined.

optional(assert(isString));

nullable(validator)

Runs the given validator unless the value is null.

nullable(assert(isString));

maybe(validator)

Runs the given validator unless the value is either null or undefined.

maybe(assert(isString));

when(predicate, validator)

Runs the given validator when the predicate is truthy.

when(isString, refute(isBlank));

each(validator)

Runs the given validator against each item in an array.

each(assert(isString));

defaultTo(value)

Provide a default value to replace null or undefined values.

defaultTo(0);

pass()

Skip validation for this field.

schema({
  name: pass(),
  age: pass()
});

Validator

A Validator represents a step in the validation sequence. You probably won't create a validator directly, but you certainly could:

const blankValidator = new Validator(input => {
  if (isBlank(value)) {
    return Validator.reject("can't be blank");
  } else {
    return Validator.resolve(value);
  }
});

validate(input)

Runs the validator against user input. This function returns a Promise.

const result = await validator.validate(data);

if (result.valid) {
  console.log(result.value);
} else {
  console.log(result.errors);
}

then(validator)

Adds another validator to the current validation chain. This method returns an entirely new validator.

validator.then(refute(isBlank));

SchemaValidator

extend(shape)

Add or overwrite the fields that a schema validates.

const user = schema({
  name: assert(isString)
});

const admin = user.extend({
  role: assert(role => role === "admin")
});

Predicates

A predicate is a function that takes a value and returns true or false.

const isBlank = value => {
  return value.trim() === "";
};

This library only includes the most essential predicate functions, because you can find thousands of predicate functions in the NPM ecosystem. Here are a few examples:

isString(value)

Checks if the value is a string.

isNumber(value)

Checks if the value is a number.

isObject(value)

Checks if the value is an object.

isBoolean(value)

Checks if the value is boolean.

isUndefined(value)

Checks if the value is undefined.

isNull(value)

Checks if the value is null.

isNil(value)

Checks if the value is null or undefined.

isBlank(value)

Checks if a string is blank.

TypeScript

Type Narrowing

This library assumes that all input is unknown by default. That means, you'll need to narrow types before calling certain functions.

Here's an example that would cause a compile-time error:

schema({
  // Error: 'unknown' is not assignable to type 'string'
  name: refute(isBlank)
});

This is by design. To address this, you'll need to narrow types by passing a type guard to assert:

schema({
  name: assert(isString).then(refute(isBlank))
});

This library includes a few type guards out of the box, but you can also write your own:

const isStringOrNumber = (value: unknown): value is string | number => {
  return typeof value === "string" || typeof value === "number";
};

Enforce an existing type with a Validator

You can ensure that your validators enforce your types.

interface User {
  name: string;
}

// Error: Property 'name' is missing in type '{}'
schema<unknown, User>({});

// Error: 'number' is not assignable to type 'string'
schema<unknown, User>({ name: assert(isNumber) });

Extract type information from a Validator

You can also generate new types from validators that you've defined:

const userSchema = schema({
  name: assert(isString),
  age: assert(isNumber);
});

type User = InferType<typeof userSchema>;