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

bitschema

v1.1.0

Published

Simple schema validation for JavaScript

Downloads

1

Readme

BitSchema

BitSchema covers most validation and transformation requirements and also supports custom parsing for special cases. Schema objects created with schema() have a schema property as well as parse, parsePartial, and parseProperty methods. Each of these methods will always return either an object containing data or invalid.

Example:
import { schema } from "bitschema";

export const Book = schema({
  title: "string|min:3",
  pages: "number|optional",
});

Now this schema can be imported and used for data transformation and validation:

import { Book } from "/schema/Book.js";

const myBook = { title: "It", pages: 350 }
const { data, invalid } = Book.parse(ctx.payload);

Handling the returned data or invalid object

BitSchema will always return an object containing either a data or invalid object.

If validation passes, a data object will be returned containing the parsed data which includes only properties defined in the schema and transformed according to its data type. For example, if pages is submitted as an input field in a web form, this arrives at the server as a string type (because all values submitted through web forms are strings). But because the specified type for pages is "number", the returned value in data.pages will be a number type ready for insertion to the database.

If validation fails, the invalid object will contain the validation errors keyed by the field name. For example if "abc" was submitted through a web form for pages, the return value for invalid.pages would be "Pages must be a number".

Validating a partial object

In some cases, you may want to validate only a partial object. For example, when updating a record, you may want to validate only the fields that were submitted. In this case, use the parsePartial() method instead of parse() like this:

const { data, invalid } = Book.parsePartial(ctx.payload);

Note that only submitted fields will be validated and returned in the data object. Any fields not submitted will be ignored regardless whether specified as optional or required (default).

Validating a single form field

You may also validate a single form field by passing in the property name and value to parseProperty like this:

const { invalid, data } = Book.parseProperty("title", "Dune");

Schema types and options

A schema item must start with a data type followed by zero or more options. All types support optional, default, label, and custom functions. optional makes the property optional.default sets the default value (effectively making it also optional). label allows you to specify a custom label for the field name used in invalid message values and uses the key set to titlecase by default. For example, if the field name is title, the default label will be "Title". The label option allows you to override this. For example, label:Book Title will result in "Book Title" being used in invalid messages instead of "Title".

Available types and their respective options include:

"string"

Returns the parsed data property as a string or returns an invalid object.

  • min:<number>: Minimum length
  • max:<number>: Maximum length
  • startsWith:<string>: Must start with specified string
  • endsWith:<string>: Must end with specified string
  • includes:<string>: Must include specified string
  • email: Must match valid email format
  • url: Must match valid url format
  • id: Must match valid MongoDB ObjectId format
  • optional: Field is optional
  • default: Set a default string value
  • label: A custom label for invalid messages
  • <string>: A custom function

"number"

Returns the parsed data property as a number or returns an invalid object.

  • min:<number>: Minimum value
  • max:<number>: Maximum value
  • integer: Must be an integer
  • optional: Field is optional
  • default: Set a default number value
  • label: A custom label for invalid messages
  • <string>: A custom function

"boolean"

Returns the parsed data property as a number or returns an invalid object. The following values are coerced to true: true, "true", "1", 1. The following values are coerced to false: false, "false", "0", 0.

  • optional: Field is optional
  • default: Set a default boolean value
  • label: A custom label for invalid messages
  • <string>: A custom function

object

Returns the object as is or returns an invalid object. Note that this type is useful for validating objects of unknown shape. If you know the shape of the object, it's better to use a nested object schema.

  • optional: Field is optional
  • default is not supported for this type
  • label: A custom label for invalid messages
  • <string>: A custom function

date

Returns the object as a date or returns an invalid object.

  • optional: Field is optional
  • default is not supported for this type
  • label: A custom label for invalid messages
  • <string>: A custom function

any

Returns the value as is. Any value is accepted.

  • optional: Field is optional
  • default is not supported for this type
  • label: A custom label for invalid messages
  • <string>: A custom function

[string], [number], [boolean], [object], [date], [any]

These are the array equivalents of the above types. For example, [string] will return an array of strings or an invalid object.

Custom functions

Any custom function can be used as a schema option in conjunction with a standard type. To do this, create a function which receives the value and returns an object containing either data or invalid, then pass the function as a second argument to the schema() function. Then reference the function name as a schema option like this:

const { data, invalid } = schema({
  pages: "number|isEven",
}, isEven);

function isEven(value) {
  return value % 2 === 0 
    ? { data: value } 
    : { invalid: "must be an even number" };
}

In line 2, we use the isEven custom function as a schema option. Then in line 3, pass in the isEven function defined in line 5 which receives the value and returns either data or invalid depending on whether the value is divisible by 2. Note that the string assigned to invalid will be prepended with the label value, e.g., "Pages must be an even number".