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

@times/data-validator

v0.6.2

Published

Simple, composable data validator for JavaScript

Downloads

164

Readme

Data Validator

Simple functional and composable JavaScript validation library

Build Status Code coverage npm version

Use

Validate an object based on a schema:

const { objectValidator, ok, err } = require('@times/data-validator');

const personSchema = {
  name: {
    type: 'string',
    required: true,
    validator: s => (s.length <= 10 ? ok() : err(`"${s}" was longer than 10`)),
  },
  age: {
    type: 'number',
    required: false,
  },
};

const validatePerson = objectValidator(personSchema);

const alice = {
  name: 'Alice',
  age: 23,
};
validatePerson(alice); // { valid: true }

const bob = {
  age: 'thirty',
};
validatePerson(bob); // { valid: false, errors: [ `Missing required field "name"`, `Field "age" failed to typecheck (expected number)` ] }

const christopher = {
  name: 'Christopher',
};
validatePerson(christopher); // { valid: false, errors: [ `At field "name": "Christopher" was longer than 10` ] }

Validate an array based on a schema:

const { arrayValidator, ok, err } = require('@times/data-validator');

const numberSchema = {
  type: 'number',
  validator: n => (n >= 10 ? ok() : err([`${n} was less than 10`])),
};

const validateNumber = arrayValidator(numberSchema);

const numbers1 = [9, 10, 11];
validateNumber(numbers1); // { valid: false, errors: [ `At item 0: 9 was less than 10` ] }

const numbers2 = ['ten', 11];
validateNumber(numbers2); // { valid: false, errors: [ `Item "ten" failed to typecheck (expected number)` ] }

Schema properties

An object schema consists of field names that map to sets of properties. Each set of properties can optionally include:

  • type: the type of the field. Can be string, number, date, array, object, function...
  • required: whether the field is required. Should be true or false
  • validator: a nested validator that should be applied to the contents of the field

An array schema can similarly have the following optional properties:

  • type: the type of the items in the array
  • validator: a nested validator that should be applied to each item in the array

Compose

Two useful functions, objectValidator and arrayValidator, are provided by default. Both accept a schema and turn it into a validator.

If these functions are insufficient, however, there are several functions available for you to build and compose your own validators.

A validator is any function with the signature data -> Result, where a Result can be constructed using the provided ok() or err() functions. err() accepts a single error message or an array of error messages.

To chain multiple validators together you can use the all or some composition functions. For example:

const validatorOne = data => data <= 3 ? ok() : err(`Data was greater than three`);

const validatorTwo = ...

// Composing with `all` returns a validator that will succeed if all of the given validators succeed
const composedValidator1 = all([
  validatorOne,
  validatorTwo
]);
const result1 = composedValidator1(data);

// Using `some` returns a validator that will succeed if at least one of the given validators succeeds
const composedValidator2 = some([
  validatorOne,
  validatorTwo,
]);
const result2 = composedValidator2(data);

You can of course write your own composition functions. A composition function must accept an array of validators and run them, somehow combining the Results into a single Result.

Converting from schemas

If you would like to use a schema beyond the supported object and array schemas, you can make use of the following exported functions:

  • fromObjectSchema: Converts an object schema to an array of validators
  • fromObjectSchemaStrict: Converts an object schema to an array of validators, including a validator that checks the object has no extra fields
  • fromArraySchema: Converts an array schema to an array of validators

You can also write your own schema conversion functions should you wish.

The resulting list of validators can then be combined into a single validator using all, some or your own composition function; this is how the default objectValidator and arrayValidator helpers work.

Contributing

Pull requests are very welcome. Please include a clear description of any changes, and full test coverage.

During development you can run tests with

yarn test

The library uses Flow for type checking. You can run Flow with

yarn flow

You can build the project with

yarn build

The build process uses Rollup to generate UMD and ES module versions of the bundle.

Contact

Elliot Davies ([email protected])