cottus

Customizable JavaScript data validator.

1
0
JavaScript

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.