Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

cottus

pustovitDmytro875MIT1.11.0

customizable JavaScript data validator

validator, validate, customize, hierarchy, .env

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

  • <input checked="" disabled="" type="checkbox"> Free of complex regexes
  • <input checked="" disabled="" type="checkbox"> All schemas described as serializable objects
  • <input checked="" disabled="" type="checkbox"> Easy to extend with own rules
  • <input checked="" disabled="" type="checkbox"> Supports complex hierarchical structures

Coming soon:

  • <input disabled="" type="checkbox"> References. issue #11
  • <input disabled="" type="checkbox"> Async rules support. issue #13

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);
    }
  2. 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('sig@viwjirgo.bn neho@sorcopaz.ml ta@inepad.ax');

console.log(admins);
// ['sig@viwjirgo.bn', 'neho@sorcopaz.ml', 'ta@inepad.ax']

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.

changelog

1.11.0 (2023-10-20)

New

1.10.13 (2023-02-07)

Chore

  • adds requirements.txt for mkdocs (dec5cfe)
  • anti-terrorism disclaimer (96327fe)
  • fixes eslint-plugin-unicorn version (dd45e9a)
  • fixes npm audit (0500470)
  • fixes some npm audit vulnerabilities (b913fee)
  • fixes some npm audit vulnerabilities (#86) (eb549de), closes #86
  • Lock file maintenance (85b7c09)
  • mkdocs path (a29de3c)
  • Update dependency danger to v11 (1779a27)
  • Update dependency nanoid to 3.1.31 [SECURITY] (#83) (89d3014), closes #83
  • Update dependency node-fetch to 2.6.7 [SECURITY] (#84) (11e82bc), closes #84
  • Update devDependencies (non-major) (01bd6c0)
  • Update devDependencies (non-major) (85a0161)
  • Update devDependencies (non-major) (#65) (d60ef28), closes #65
  • Update devDependencies (non-major) (#66) (69aac8f), closes #66
  • Update devDependencies (non-major) (#92) (f492769), closes #92

Docs

1.10.12 (2022-10-08)

Docs

  • adds usage samples to documentation (0f128d9)

1.10.11 (2022-09-06)

Docs

  • update keywords and description (0f714b1)

1.10.10 (2022-07-28)

Chore

Fix

  • empty values in assembler. closes #49 (1a77e37), closes #49

1.10.9 (2022-07-28)

Docs

1.10.8 (2022-07-27)

Chore

Docs

  • adds extra documentation (52cb6eb)
  • ads basic documentation (88c37fc)

1.10.7 (2022-02-28)

Chore

  • Lock file maintenance (#30) (2f03dd7), closes #30
  • replace path.resolve to path.normalize in tests. windows compartibility (5a21e89)
  • Update devDependencies (non-major) (#16) (23cadea), closes #16
  • Update devDependencies (non-major) (major) (#17) (85d5b26), closes #17

Docs

1.10.6 (2022-02-01)

Chore

  • fixes some npm audit vulnerabilities (#27) (15ef37e), closes #27
  • resolve path in tests depending on os. fixes #29 (bbced33), closes #29

Docs

1.10.5 (2022-01-28)

Chore

  • ignore encryptionKey tests in npt (cbf40f6)

Upgrade

  • Update dependency myrmidon to v1.7.2 (#26) (2eb913a), closes #26

1.10.4 (2022-01-28)

Chore

  • fixes some npm audit vulnerabilities (b632291)
  • fixes some npm audit vulnerabilities (#23) (07be8a9), closes #23
  • Lock file maintenance (#12) (3b54870), closes #12

Docs

1.10.3 (2022-01-22)

Chore

  • (ci) fix gitleaks version (badd1c1)
  • adds telegra.ph release notes (aa811a5)
  • calc fossa results in cirrus (b2b48c1)
  • fixes some npm audit vulnerabilities (9330c38)
  • fixes some npm audit vulnerabilities (f7a14d5)
  • integrate lalaps (dd4f238)
  • replace appveyor to actions (13aff75)
  • update deps badge (0836169)
  • upgrade semantic-release to v.19 [security] (0888454)

Docs

1.10.2 (2022-01-21)

Fix

  • every rule returns validated values instead inputs (74e8659)

1.10.1 (2022-01-04)

Fix

1.10.0 (2021-11-18)

New

1.9.1 (2021-11-16)

Docs

  • adds readme (cf60088)
  • integrate rules docs with .code-chronicle (50845d9)

1.9.0 (2021-11-14)

New

1.8.0 (2021-11-11)

Chore

  • adds more min/max tests (6d3d14d)

New

1.7.0 (2021-11-11)

New

1.6.0 (2021-11-10)

Chore

  • skip encryptionKey.test.js from gitleaks (205d289)

New

1.5.0 (2021-11-09)

New

1.4.0 (2021-11-09)

New

  • adds 'encryptionKey' and 'base64' rules. #10 (bb23357), closes #10

1.3.0 (2021-11-08)

New

1.2.0 (2021-11-07)

New

  • adds 'number' and 'integer' rules. #10 (eac38c2), closes #10

1.1.0 (2021-11-07)

New

  • adds hierarhy rules [every, attributes]. #10 (3142838), closes #10
  • handle simultanious errors (7a1369d)

1.0.0 (2021-11-06)

Chore

  • 'Chore' semanticCommitType for updating devDependencies (4bf79e1)
  • (git) Add logs to gitignore (d4d2077)
  • (refactor) remove unused argument (6f28b59)
  • (test) helper packages for tests (e195b58)
  • (test) working with tmp dir for test factory (cfeafbc)
  • (tests) clearCache on module load is optional (96c2ae5)
  • (tests) moves load to factory (4acb941)
  • additional quotes in glob pattern (f6d15cf)
  • adds a security policy (ed86aba)
  • adds 'typo' PR template (e20404d)
  • adds appveyor (d560b4e)
  • adds bump strategy for devDependencies (non-major) (03c9587)
  • adds CIRCLE_SKIP_DEPLOY variable (231549d)
  • adds circle-ci conditions (5a40980)
  • adds CODE_OF_CONDUCT (a969a8d)
  • adds commitlint (38ded63)
  • adds danger to circle-ci (ae48ac3)
  • adds danger to validate pr (7fb7040)
  • adds danger token to circle (82f4156)
  • adds dangerfile to npm ignore (8842c70)
  • adds dummy line to calc coverage (800de67)
  • adds empty line to pr comment (36d8a09)
  • adds gitleaks to circle pipeline (114946e)
  • adds jscpd to ignore (8520cea)
  • adds lock file lint (f5a4679)
  • adds pr context (ce163d9)
  • adds sonarcloud config (c92973d)
  • adds sponsorships (35ed8e0)
  • adds stabilityDays to renovate (3b262bc)
  • adds target branch to semantic release (c4fb3f1)
  • adds technical dept check (e16a8e2)
  • adds test-results to circle-ci (767c5b3)
  • adds tests for packing process (9b9602d)
  • adds tests for prior node versions (4b00012)
  • adds trusted bots to danger (892f4a1)
  • adds whitesorce bolt bot (0888eee)
  • change extention of test files to .test.js (d84ac03)
  • change renovate schedule (b983eab)
  • change tgz label (5e0e512)
  • combine mine packages in renovate updates (54c97b8)
  • contributor login in danger message (76349e6)
  • corrected extglob matching (72a2201)
  • corrected pack pattern (273497a)
  • create auto pr for major dependencies (d2583a6)
  • deploy ci as single command (96c2800)
  • deploy in circle-ci (a62a5f2)
  • disable build for coverage check (0b6e984)
  • dont pin devDeps in renovate (5fb0e8d)
  • dont store package-tests artifacts (50ebff1)
  • drop semantic-release preinstalled plugins (69b1950)
  • enhance own updates commit messages (49a2365)
  • exit code 0 when skip (f6ee0bf)
  • export default in tests (9d210e6)
  • fill test entry with template (9177859)
  • fix json in renovate (8ad7928)
  • fixes audit (14597ff)
  • fixes audit [devDependencies] (d08b1fc)
  • fixes Breaking increment in semantic-release (d1c4d53)
  • fixes ci (0576a01)
  • Fixes danger-pr in circe-ci (adff8b3)
  • fixes debt typo in travis job (f9fd463)
  • fixes later schedule (a0cfb5c)
  • fixes lint (ca74998)
  • fixes npm audit (c3beccd)
  • fixes package process (364e26b)
  • fixes prevent require handler (7923f0e)
  • fixes renovate config (982abaf)
  • fixes renovate config (05c5bc5)
  • fixes spellcheck in bugreport (7d754b6)
  • ignoring all for npm packaging (409201a)
  • integrate APPVEYOR_BUILD_ID to build tests (16cdd48)
  • integrate fossa (b65e961)
  • integrate node-package-tester (9d53bf3)
  • inverse logical condition (65dd0ad)
  • Lock file maintenance (29fe760)
  • Lock file maintenance (9892cc5)
  • Lock file maintenance (98e62b3)
  • Lock file maintenance (7af4484)
  • Lock file maintenance (1ffc991)
  • Lock file maintenance (47bfacf)
  • Lock file maintenance (19c2389)
  • Lock file maintenance (2b00aec)
  • Lock file maintenance (dea06c9)
  • Lock file maintenance (e0043d8)
  • Lock file maintenance (5d305a8)
  • Lock file maintenance (cdf4f11)
  • Lock file maintenance (3291a21)
  • multi os tests for travis (7c8ce28)
  • not allow to fail on node 16 (22ed683)
  • not fail package if no tmp exists (5693813)
  • package-tester improvements (d5d868b)
  • prevent package:test from using devdependencies (dc896f3)
  • removes unused devDependencies (ddb100a)
  • run pr workflow only for pull requests (03e0b08)
  • set myself as default assignee in pr (0dcd0ce)
  • set YARGS_MIN_NODE_VERSION 10 (9b6bef9)
  • split circle ci jobs (9f75a6b)
  • telegram notifications on release (3a8036a)
  • test-security in separete ci job (a4bd846)
  • test-security in separete ci job (9559dbc)
  • tests/entry.js module resolving (c840f8b)
  • update .renovaterc to automerge after successfull checks (2e76ceb)
  • update default renovate rules (7e83bc4)
  • Update dependency @rollup/plugin-commonjs to v19 (bf29948)
  • Update dependency @rollup/plugin-node-resolve to v13 (265fd82)
  • Update dependency babel-plugin-module-resolver to v4 (b8eb86f)
  • Update dependency eslint to v7 (0e79e0f)
  • Update dependency eslint-plugin-regexp to ^0.12.0 (51ff304)
  • Update dependency eslint-plugin-regexp to ^0.13.0 (#36) (3a8d3ec), closes #36
  • Update dependency eslint-plugin-sonarjs to ^0.9.0 (81d9681)
  • Update dependency eslint-plugin-unicorn to v33 (bfa00ff)
  • Update dependency eslint-plugin-unicorn to v34 (#34) (86efbac), closes #34
  • Update dependency fs-extra to v10 (a0adecc)
  • Update dependency glob-parent to 5.1.2 [SECURITY] (c957512)
  • Update dependency husky to v7 (3578711)
  • Update dependency mocha to v8 (627a45b)
  • Update dependency mocha to v9 (93b7a17)
  • Update dependency nyc to v15 (1caf199)
  • Update dependency uuid to v8 (ebae34b)
  • Update devDependencies (non-major) (609151a)
  • Update devDependencies (non-major) (5b1a6c3)
  • Update devDependencies (non-major) (51200bf)
  • Update devDependencies (non-major) (33211c3)
  • Update devDependencies (non-major) (#48) (b3f6184), closes #48
  • Update devDependencies (non-major) to v13 (6894ad9)
  • update eslint (6b174b1)
  • update eslint (4aac03c)
  • update eslint-config-incredible (2f39edb)
  • update eslint-config-incredible (58c31d2)
  • Update issue templates (8fdb1af)
  • update lock file (4ffb878)
  • Update pr template (1d4eb34)
  • update semantic release rules (a075dab)
  • update semantic to use commit convention (7e079b2)
  • Update semantic-release monorepo (b7ab2b1)
  • update travis badge (e159104)
  • updates semanticCommitType rule (1a1d119)
  • upgrade circle-ci to 2.1 (fab79a9)
  • use danger for internall pr (d838ede)
  • use incredible eslint config (b03d74a)
  • use native tarball generation (eeefda5)
  • using static test entry (21e5b7d)

Docs

  • adds codefactor badge (52a2a14)
  • adds Fossa badge (60a6703)
  • adds node releases roadmap (ba16142)
  • change travis badge to circle-ci (ebabb61)
  • changes size-url (ecc2fc2)
  • fixes spellcheck (bc06d85)
  • move Contributing Guidelines to separate file. (081e4ed)
  • prettify modified_files as markdown list in pr (6397f60)
  • prettify modified_files list in pr (ecce71a)
  • removes ) from badge (b986009)
  • reorder badges (ed6d250)
  • update badges (ffe57a1)
  • update snyk badge (a7fbb1d)
  • update year in license (1aa3c35)

Fix

New