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

legitjs

v0.1.1

Published

Lightweight objects and strings validation for Node.js

Downloads

10

Readme

legit.js 0.1.1

Lightweight objects and strings validation for Node.js.

Usage

Create a schema and use it to validate data.

There are two equivalent usages:

  • schema.test(data)
  • legit.mize(schema, data)

These functions return null if there was no error validating the data. If the data didn't fit the schema, they return a description of the error (either a String, an Array, or a Map/Object).

    var schema = legit.Number().min(5).max(10);
    
    var err1 = schema.test(30);  // err1 = 'Greater than max'
    var err2 = schema.test(6);   // err2 = null
    
    // alternative usage:
    err1 = legit.mize(schema, 30);  // err1 = 'Greater than max'
    err2 = legit.mize(schema, 6);   // err2 = null

Note: The keyword "new" should not be used when creating an instance of a schema.

Real world example

Suppose you have some incoming network data and you want to validate it before using/processing it.

    // Create the schema
    var userSchema = legit.Map().strict()
        .key("user", legit.String().min(3).max(20))
        .key("age", legit.Number().min(21));
    
    // Validate incoming data
    var err = userSchema.test(data);

    if (err) {
        // Data did not fit the schema.
        // Check 'err' to learn what went wrong.
        console.log(err);
    }
    else {
        // Data successfully validated!
        // Now you can use/process it with confidence.
        ...
    }

Installing and Importing

Using NPM, run the following command in your project's root directory.

$ npm install legitjs

In your Node.js program:

    var legit = require("legitjs");

Types Of Schemas

legit.Any()

Accepts anything.

Example:

        var schema = legit.Any();
        schema.test("POTATO")   // null
        schema.test([1, 2, 3])  // null

legit.Null()

Accepts only null.

Example:

        var schema = legit.Null();
        schema.test("Hello")    // 'Not null'
        schema.test(null)       // null

legit.Boolean()

Accepts only Booleans.

Modifiers:

  • none(): Accepts null and undefined.

Example:

        var schema = legit.Bool();
        schema.test(123)    // 'Not a boolean'
        schema.test(null)   // 'Boolean is null or undefined'
        schema.test(true)   // null

        var schema2 = legit.Bool().none()
        schema2.test(null)   // null

legit.Number()

Accepts only Numbers.

Modifiers:

  • none(): Accepts null and undefined.
  • min(a): Sets minimum allowed value (a).
  • max(b): Sets maximum allowed value (b).

Example:

        var schema = legit.Number().min(-5).max(30);
        schema.test(-5);    // null
        schema.test(31);    // 'Greater than maximum'
        schema.test(true);  // 'Not a number'
        schema.test(null);  // 'Number is null or undefined'

legit.String()

Accepts only Strings.

Modifiers:

  • none(): Accepts null and undefined.
  • min(a): Sets minimum allowed length (a).
  • max(b): Sets maximum allowed length (b).
  • regex(e): Sets a regular expression to use (e).

Example:

        var schema = legit.String().max(12).regex(/(\w+)\s(\w+)/);

        schema.test("JohnSmith");
        // 'Regular expression didn't match'
        
        schema.test("John Smith");
        // null
        
        schema.test("John R. Smith");
        // 'Greater than maxmimum'

legit.Array()

Accepts only Arrays. Can be used recursively with all other schemas.

You have two options when using legit.Array():

  • Set a schema to validate all objects of the array by using .type(schema) once.
  • Set a different schema for each item by using .item(schema) once for each item, in the expected order.

Modifiers:

  • none(): Accepts null and undefined.
  • min(a): Sets minimum allowed length (a). Only affects same-type arrays.
  • max(b): Sets maximum allowed length (b). Only affects same-type arrays.
  • type(s): Sets a schema (s) to test all array items. Establishes array as same-type.
  • item(s): Sets a schema (s) to test a single item of the array. Establishes array as different-type.
  • strict(): Rejects arrays with length greater than expected. Only affects different-type arrays.

Example:

        // Same-type array
        var schema = legit.Array().max(4)
            .type(legit.Number().min(0).max(10));

        schema.test([1, 2, 3, 4]);
        // null
        
        schema.test([1, 2, 3, 4, 5]);
        // 'Greater than maxmimum'
        
        schema.test([5, 11]);
        // [null, 'Greater than maximum']
        
        // Different-type array
        var schema = legit.Array().strict()
            .item(legit.String().min(3).max(12))
            .item(legit.Number().min(21));

        schema.test(["John Smith", 25]);
        // null

        schema.test(["John", 25, true]);  
        // [ null, null,
        //   'More items than expected (Array in strict mode)' ]
        
        schema.test(["John Smith Jr.", 20]);
        // [ 'Greater than maximum', 'Less than minimum' ]

legit.Map()

Accepts only Maps/Objects. Can be used recursively with all other schemas.

Modifiers:

  • none(): Accepts null and undefined.
  • strict(): Rejects maps with unexpected keys.
  • key(n, s): Sets an expected key-value pair. n is the expected key and s is the schema that will be used to validate the value.

Example:

    var schema = legit.Map().strict()
        .key("user", legit.String().min(3).max(12))
        .key("age", legit.Number().min(21));

    schema.test({
        "user": "John Smith",
        "age": 25
    }) 
        // null
    
    schema.test({
        "user": "John Smith Junior",
        "age": 16
    })
        // { user: 'Greater than maximum',
        //    age: 'Less than minimum' } 

Support/Contact

Feel free to contact me with questions, suggestions, or comments.

I hope you enjoy using legit.js as much as I enjoyed writing it.

If you come across any issues, please report them.