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

js-data-validator

v1.5.0

Published

Data validator and normalizer

Downloads

7

Readme

js-data-validator

Data validator and normalizer

Introduction

Important Note: This is work in progress. Please, don't use it in production yet.

This work is inspired by the awesome joi object schema validator.

Why another validation module? Error messages! When validating incoming data data in an API endpoint, we would like to inform clients with custom meaningful messages describing what's wrong with there requests. There is no way to do that with joi.

Example

const Jdv = require('js-data-validator');

const schema = Jdv.object().keys({
  userName: Jdv.string().required('my custom error message about missing "userName"'),
  password: Jdv.string().required('my custom error message about missing "password"')
                        .notEmpty('my custom error message about empty "password"'),
  avatarUrl: Jdv.string().defaultsTo('http://example.com/avatars/default'),
  bonuses: Jdv.integer('my custom error message about "bonuses" being non-integer')
              .nullable()
});

const incomingData = {
  userName: 'John Smith',
  bonuses: null
};

const { data, errors } = Jdv.validate(schema, incomingData);

if (errors.length) {
  res.status(400).json({ errorMessages: errors.join(', ')});
  return;
}

// Here start using data

API Reference

Jdv

validate(schema, data)

Validates data against schema and returns normalized data if the schema prescribes doing it. The method doesn't mutate passed data.

  • schema {Object} - validation schema.

  • data {Any} - data to be validated and normalized.

Returns Object with properties:

  • data {Any} - normalized data.

  • errors {Array<String>} - collection of error messages.

any()

Generates a schema that validates any value.

object()

Generates a schema to validate/normalize an object.

object.keys(obj)

Defines validation rules for object properties.

  • obj {Object} - Object where each key is assigned a validation schema.
object.key.required([msg])

Creates validation rule for a key to be present in the object.

  • msg {String} - Optional error message. Defaults to an empty string.
object.key.defaultsTo([value])

Creates normalization rule for a missing property in the data object to be set to the specified value.

  • value {Any} - Optional. Value to be assigned to the missing property. Defaults to null.
object.key.nullable()

Creates validation rule for a key to allow it contain null value.

object.keysCaseInsensitive()

Creates validation and normalization rule according to which object's keys are treated case insensitively.

Please note that if the data object has several keys that are case insensitively equal, the normalized data object will receive the value of the latest keys.

Example:

const dataToProcess = {
  aa: 'foo',
  aA: 'bar',
  AA: 'baz'
};

const schema = Jdv.object().keys({
  aA: Jdv.string()
}).keysCaseInsensitive();

const { data} = Jdv.validate(schema, dataToProcess);

console.dir(data);
// { aA: 'baz' }
// Note that the normalized key name is as it is described by the schema, and its value is set
// to the value of the last case insensitively equal keys.

array({ [schema], [msg] })

Generates a schema to validate/normalize an array.

  • opts {Object} - Optional. Options:

    • schema {Object} - Optional. Validation schema to be applied to each element of the array. If no schema passed, the array elements are not validated/normalized.

    • msg {String} - Optional. Error message to be included in the returned errors collection in case the passed data is not an array. Defaults to an empty string.

Example:

const schema = Jdv.object().keys({
  userNames: Jdv.array({
    schema: Jdv.string().notEmpty('my custom error message'),
    msg: 'my custom error message for the case "userNames" is not an array'
  }).notEmpty('my custom error message for the case "userNames" is an empty array')
});
array.notEmpty([msg])

Creates validation rule for not allowing the array to be empty.

  • msg {String} - Optional error message. Defaults to an empty string.

record({ [schemaForKey], [schemaForValue], [msg] })

Generates a schema to validate/normalize a record of key-value pairs (think of TypeScript's type Record<K, V>).

  • opts {Object} - Optional. Options:

    • schemaForKey {Object} - Optional. Validation schema to be applied to each key of the record. If no schema passed, keys are not validated/normalized.

    • schemaForValue {Object} - Optional. Validation schema to be applied to each value of the record. If no schema passed, values are not validated/normalized.

    • msg {String} - Optional. Error message to be included in the returned errors collection in case the passed data is not a record. Defaults to an empty string.

Example:

const schema = Jdv.record({
  schemaForKey: Jdv.uuid('keys must be UUIDs'),
  schemaForValue: Jdv.ISODateString('valus must be ISO date strings'),
  msg: 'expected a record'
}).notEmpty('record must not be empty');
record.notEmpty([msg])

Creates validation rule for not allowing the record to be empty.

  • msg {String} - Optional error message. Defaults to an empty string.

string()

Generates a schema to validate/normalize a string.

Any validated value is coerced to a string using String() constructor function.

string.notEmpty([msg])

Creates validation rule for not allowing the string to be empty.

  • msg {String} - Optional error message. Defaults to an empty string.
string.transform(fn)

Creates transformation rule.

Transformation is applied before validate but after notEmpty.

  • fn {Function} - User defined transformation function. The function is passed the string and supposed to return the transformed string. If fn is undefined or not a function, no transformation is applied.

Example:

const myTransformFn = val => val + 'a';
const schema = Jdv.string().transform(myTransformFn);
string.validate(fn, [msg])

Creates user defined validation rule.

  • fn {Function} - User defined validation function. The function is passed the string and supposed to return any value. If the returned value is falsey, validation failes. If fn is undefined or not a function, validation always succeeds.

  • msg {String} - Optional error message. Defaults to an empty string.

Example:

const myValidationFn = val => val === 'abc';
const schema = Jdv.string().validate(myValidationFn, 'expected "abc" string');

integer([msg])

Generates a schema to validate/normalize an integer value.

Any validated value is tried to be parsed into an integer.

  • msg {String} - Optional error message. Defaults to an empty string.

Example:

const schema = Jdv.integer('my custom error message in case the value is not an integer')
                  .max(100, 'my custom error message in case it is greater')
                  .min(0, 'my custom error message in case it is less');
});
integer.max(value, [msg])

Creates validation rule for a value to be less or equal to the passed maximum value.

  • value {Integer} - Maximum value to compare with.

  • msg {String} - Optional error message. Defaults to an empty string.

integer.min(value, [msg])

Creates validation rule for a value to be greater or equal to the passed minimum value.

  • value {Integer} - Minimum value to compare with.

  • msg {String} - Optional error message. Defaults to an empty string.

number([msg])

Generates a schema to validate/normalize a number value.

Any validated value is tried to be parsed into a number.

  • msg {String} - Optional error message. Defaults to an empty string.
number.max(value, [msg])

Creates validation rule for a value to be less or equal to the passed maximum value.

  • value {Number} - Maximum value to compare with.

  • msg {String} - Optional error message. Defaults to an empty string.

number.min(value, [msg])

Creates validation rule for a value to be greater or equal to the passed minimum value.

  • value {Number} - Minimum value to compare with.

  • msg {String} - Optional error message. Defaults to an empty string.

boolean()

Generates a schema to validate/normalize a boolean value.

Before being validated, the value is coerced to a boolean using Boolean() constructor function.

ISODateString([msg])

Generates a schema to validate a string to be a correct UTC date representation in format YYYY-MM-DDTHH:MM:SS.sssZ.

  • msg {String} - Optional error message. Defaults to an empty string.

If validation fails, the method normalizes the value to null.

uuid([msg])

Generates a schema to validate a string to be a correct UUID.

  • msg {String} - Optional error message. Defaults to an empty string.

If validation fails, the method normalizes the value to null.