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

cottus

v1.11.0

Published

customizable JavaScript data validator

Downloads

1,754

Readme

Logo

cottus

Customizable JavaScript data validator.

Version Bundle size Downloads

CodeFactor SonarCloud Codacy Scrutinizer

Dependencies Security Build Status Coverage Status

Commit activity FOSSA License Made in Ukraine

🇺🇦 Help Ukraine

I woke up on my 26th birthday at 5 am from the blows of russian missiles. They attacked the city of Kyiv, where I live, as well as the cities in which my family and friends live. Now my country is a war zone.

We fight for democratic values, freedom, for our future! Once again Ukrainians have to stand against evil, terror, against genocide. The outcome of this war will determine what path human history is taking from now on.

💛💙 Help Ukraine! We need your support! There are dozen ways to help us, just do it!

Table of Contents

Features

  • [x] Free of complex regexes
  • [x] All schemas described as serializable objects
  • [x] Easy to extend with own rules
  • [x] Supports complex hierarchical structures

Coming soon:

Motivation

There are several nice validators in the JS world (livr, joi), but no one satisfied all my needs entirely.

Another big question here is why not just use regular expressions? Regexp is an undoubtedly powerful tool, but has its own cons. I am completely tired of searching for valid regexp for any standard validation task. Most of them need almost scientific paper to describe patterns. They are totally unpredictable when faced with arbitrary inputs, hard to maintain, debug and explain.

So, that is another JS validator, describing my view for the modern validation process.

Requirements

Platform Status

To use library you need to have node and npm installed in your machine:

  • node >=10
  • npm >=6

Package is continuously tested on darwin, linux, win32 platforms. All active and maintenance LTS node releases are supported.

Installation

To install the library run the following command

  npm i --save cottus

Usage

Commonly usage is a two steps process:

  1. Constructing validator from a schema
  2. Running validator on arbitrary input.
import cottus from 'cottus';

const validator = cottus.compile([
    'required', { 'attributes' : {
        'id'       : [ 'required', 'uuid' ],
        'name'     : [ 'string', { 'min': 3 }, { 'max': 256 } ],
        'email'    : [ 'required', 'email' ],
        'contacts' : [ { 'every' : {
            'attributes' : {
                'type' : [
                    'required',
                    { 'enum': [ 'phone', 'facebook' ] }
                ],
                'value' : [ 'required', 'string' ]
            }
        } } ]
    } }
]);

try {
    const valid = validator.validate(rawUserData);

    console.log('Data is valid:', valid);
} catch (error) {
    console.error('Validation Failed:', error);
}

Check list of available rules at reference

Errors

CottusValidationError would be returned in case of validation failure.

There are 2 ways of identifying this error:

  1. recommended: verify the affiliation to the class:
import { ValidationError } from 'cottus';

if (error instanceof ValidationError) {
    console.error(error.prettify);
}
  1. soft way: check isValidationError property:
try {
    const valid = validator.validate(rawUserData);

    console.log('Data is valid:', valid);
} catch (error) {
    if (error.isValidationError) {
        console.error('Validation Failed:', error);
    }

    console.error('Unknown error occured:', error);
}

To get a pretty hierarchical tree with error codes, use:

console.error(error.prettify);

To get full error data, use:

console.error(error.hash);

Assembler

if you need to gather a flat list of values into the hierarchy and validate, use the Assembler module.

Typical use case - transforming environment variables into the config:

import { Assembler } from 'cottus';

const assembler = new Assembler(cottus, schema);
const e = process.env;

const schema = {
    mongo : !!e.MONGO_CONNECTION_STRING ? {
        url : { $source: '{MONGO_CONNECTION_STRING}', $validate: [ 'required', 'url' ] },
        db  : { $source: '{MONGO_DB_NAME}', $validate: [ 'required', 'string' ] }
    } : null,
    redis : {
        port     : { $source: '{REDIS_PORT}', $validate: [ 'required', 'port' ] },
        host     : { $source: '{REDIS_HOST}', $validate: [ 'required', 'hostname' ] },
        db       : { $source: '{REDIS_DB}', $validate: [ 'integer' ] },
        password : { $source: '{REDIS_PASSWORD}', $validate: [ 'string' ] },
        username : { $source: '{REDIS_USER}', $validate: [ 'string' ] }
    },
    'administrators' : {
        $source   : { type: 'complex_array', prefix: 'ADMIN_' },
        $validate : {
            'login'     : { $source: '{_LOGIN}', $validate: [ 'required', 'email' ] },
            'password'  : { $source: '{_PASSWORD}', $validate: [ 'string' ] },
            permissions : {
                $source   : { type: 'simple_array', prefix: '_PERMISSIONS_' },
                $validate : { 'enum': [ 'read', 'write' ] }
            }
        }
    }
};

assembler.parse();
const config = assembler.run(process.env);

schema should be a hierarchical object. The deepest properties can be one of the following keywords:

  • $source: can be a placeholder '{REDIS_PORT}' or an object: { type: 'complex_array', prefix: 'USER_' }. Next types allowed:
    • complex_array: array of objects
    • simple_array: array of primitives
    • constant: a value
  • $validate: cottus schema.

To check more examples, see implementation section.

Custom rules

cottus can be extended with new rules.

import cottus, { BaseRule } from 'cottus';

class Split extends BaseRule {
    static schema = 'split';

    validate(input) {
        const symbol = this.params;

        return input.split(symbol);
    }
}

cottus.addRules([
    Split
]);

now rule split can be used in cottus schema:

const validator = cottus.compile([
    'required',
    { 'split': ' ' },
    { every: 'email' }
]);

const admins = validator.validate('[email protected] [email protected] [email protected]');

console.log(admins);
// ['[email protected]', '[email protected]', '[email protected]']

to throw validation error from the custom rule, use predefined errors:

import { errors } from 'cottus';

const { NOT_ALLOWED_VALUE } = errors;

if (!valid) throw new NOT_ALLOWED_VALUE();

or create own error:

import { BaseError } from 'cottus';

class UnsafeNumberError extends BaseError {
    message = 'The number is not within the safe range of JavaScript numbers';
    code = 'UNSAFE_NUMBER';
}

Implementations

Are you looking for more examples?

Validation

Custom rules

  • ianus: split string into array

Assembler

  • ianus: transform process.env into config
  • ianus: load data from env or mongo collection.

Contribute

Make the changes to the code and tests. Then commit to your branch. Be sure to follow the commit message conventions. Read Contributing Guidelines for details.