• This repository has been archived on 16/Feb/2021
  • Stars
    star
    400
  • Rank 107,843 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Validation library based on type combinators

build status dependency status npm downloads

A general purpose JavaScript validation library based on type combinators

Features

  • concise yet expressive syntax
  • validates native types, refinements, objects, lists and tuples, enums, unions, dicts, intersections
  • validates structures with arbitrary level of nesting
  • detailed informations on failed validations
  • lightweight alternative to JSON Schema
  • reuse your domain model written with tcomb

Documentation

Basic usage

If you don't know how to define types with tcomb you may want to take a look at its README file.

The main function is validate:

validate(value, type, [options]) -> ValidationResult
  • value the value to validate
  • type a type defined with the tcomb library
  • options (optional) is an object with the following keys
    • path: Array<string | number> path prefix for validation
    • context: any passed to getValidationErrorMessage (useful for i18n)
    • strict: boolean (default false) if true no additional properties are allowed while validating structs

returns a ValidationResult object containing the result of the validation

Note.

  • options can be an array (as path prefix) for backward compatibility (deprecated)

Example

var t = require('tcomb-validation');
var validate = t.validate;

validate(1, t.String).isValid();   // => false
validate('a', t.String).isValid(); // => true

You can inspect the result to quickly identify what's wrong:

var result = validate(1, t.String);
result.isValid();             // => false
result.firstError().message;  // => 'Invalid value 1 supplied to String'

// see `result.errors` to inspect all errors

Primitives

// null and undefined
validate('a', t.Nil).isValid();       // => false
validate(null, t.Nil).isValid();      // => true
validate(undefined, t.Nil).isValid(); // => true

// strings
validate(1, t.String).isValid();   // => false
validate('a', t.String).isValid(); // => true

// numbers
validate('a', t.Number).isValid(); // => false
validate(1, t.Number).isValid();   // => true

// booleans
validate(1, t.Boolean).isValid();    // => false
validate(true, t.Boolean).isValid(); // => true

// optional values
validate(null, maybe(t.String)).isValid(); // => true
validate('a', maybe(t.String)).isValid();  // => true
validate(1, maybe(t.String)).isValid();    // => false

// functions
validate(1, t.Function).isValid();              // => false
validate(function () {}, t.Function).isValid(); // => true

// dates
validate(1, t.Date).isValid();           // => false
validate(new Date(), t.Date).isValid();  // => true

// regexps
validate(1, t.RegExp).isValid();    // => false
validate(/^a/, t.RegExp).isValid(); // => true

Refinements

You can express more fine-grained contraints with the refinement syntax:

// a predicate is a function with signature: (x) -> boolean
var predicate = function (x) { return x >= 0; };

// a positive number
var Positive = t.refinement(t.Number, predicate);

validate(-1, Positive).isValid(); // => false
validate(1, Positive).isValid();  // => true

Objects

Structs

// an object with two numerical properties
var Point = t.struct({
  x: t.Number,
  y: t.Number
});

validate(null, Point).isValid();            // => false
validate({x: 0}, Point).isValid();          // => false, y is missing
validate({x: 0, y: 'a'}, Point).isValid();  // => false, y is not a number
validate({x: 0, y: 0}, Point).isValid();    // => true
validate({x: 0, y: 0, z: 0}, Point, { strict: true }).isValid(); // => false, no additional properties are allowed

Interfaces

Differences from structs

  • also checks prototype keys
var Serializable = t.interface({
  serialize: t.Function
});

validate(new Point(...), Serializable).isValid(); // => false

Point.prototype.serialize = function () { ... }

validate(new Point(...), Serializable).isValid(); // => true

Lists and tuples

Lists

// a list of strings
var Words = t.list(t.String);

validate(null, Words).isValid();                  // => false
validate(['hello', 1], Words).isValid();          // => false, [1] is not a string
validate(['hello', 'world'], Words).isValid();    // => true

Tuples

// a tuple (width x height)
var Size = t.tuple([Positive, Positive]);

validate([1], Size).isValid();      // => false, height missing
validate([1, -1], Size).isValid();  // => false, bad height
validate([1, 2], Size).isValid();   // => true

Enums

var CssTextAlign = t.enums.of('left right center justify');

validate('bottom', CssTextAlign).isValid(); // => false
validate('left', CssTextAlign).isValid();   // => true

Unions

var CssLineHeight = t.union([t.Number, t.String]);

validate(null, CssLineHeight).isValid();    // => false
validate(1.4, CssLineHeight).isValid();     // => true
validate('1.2em', CssLineHeight).isValid(); // => true

Dicts

// a dictionary of numbers
var Country = t.enums.of(['IT', 'US'], 'Country');
var Warranty = t.dict(Country, t.Number, 'Warranty');

validate(null, Warranty).isValid();             // => false
validate({a: 2}, Warranty).isValid();           // => false, ['a'] is not a Country
validate({US: 2, IT: 'a'}, Warranty).isValid(); // => false, ['IT'] is not a number
validate({US: 2, IT: 1}, Warranty).isValid();   // => true

Intersections

var Min = t.refinement(t.String, function (s) { return s.length > 2; }, 'Min');
var Max = t.refinement(t.String, function (s) { return s.length < 5; }, 'Max');
var MinMax = t.intersection([Min, Max], 'MinMax');

MinMax.is('abc'); // => true
MinMax.is('a'); // => false
MinMax.is('abcde'); // => false

Nested structures

You can validate structures with an arbitrary level of nesting:

var Post = t.struct({
  title: t.String,
  content: t.String,
  tags: Words
});

var mypost = {
  title: 'Awesome!',
  content: 'You can validate structures with arbitrary level of nesting',
  tags: ['validation', 1] // <-- ouch!
};

validate(mypost, Post).isValid();             // => false
validate(mypost, Post).firstError().message;  // => 'tags[1] is `1`, should be a `Str`'

Customise error messages

You can customise the validation error message defining a function getValidationErrorMessage(value, path, context) on the type constructor:

var ShortString = t.refinement(t.String, function (s) {
  return s.length < 3;
});

ShortString.getValidationErrorMessage = function (value) {
  if (!value) {
    return 'Required';
  }
  if (value.length >= 3) {
    return 'Too long my friend';
  }
};

validate('abc', ShortString).firstError().message; // => 'Too long my friend'

How to keep DRY?

In order to keep the validation logic in one place, one may define a custom combinator:

function mysubtype(type, getValidationErrorMessage, name) {
  var Subtype = t.refinement(type, function (x) {
    return !t.String.is(getValidationErrorMessage(x));
  }, name);
  Subtype.getValidationErrorMessage = getValidationErrorMessage;
  return Subtype;
}

var ShortString = mysubtype(t.String, function (s) {
  if (!s) {
    return 'Required';
  }
  if (s.length >= 3) {
    return 'Too long my friend';
  }
});

Use cases

Form validation

Let's design the process for a simple sign in form:

var SignInInfo = t.struct({
  username: t.String,
  password: t.String
});

// retrieves values from the UI
var formValues = {
  username: $('#username').val().trim() || null,
  password: $('#password').val().trim() || null
};

// if formValues = {username: null, password: 'password'}
var result = validate(formValues, SignInInfo);
result.isValid();             // => false
result.firstError().message;  // => 'Invalid value null supplied to /username: String'

JSON schema

If you don't want to use a JSON Schema validator or it's not applicable, you can just use this lightweight library in a snap. This is the JSON Schema example of http://jsonschemalint.com/

{
  "type": "object",
  "properties": {
    "foo": {
      "type": "number"
    },
    "bar": {
      "type": "string",
      "enum": [
        "a",
        "b",
        "c"
      ]
    }
  }
}

and the equivalent tcomb-validation counterpart:

var Schema = t.struct({
  foo: t.Number,
  bar: t.enums.of('a b c')
});

let's validate the example JSON:

var json = {
  "foo": "this is a string, not a number",
  "bar": "this is a string that isn't allowed"
};

validate(json, Schema).isValid(); // => false

// the returned errors are:
- Invalid value "this is a string, not a number" supplied to /foo: Number
- Invalid value "this is a string that isn't allowed" supplied to /bar: "a" | "b" | "c"

Note: A feature missing in standard JSON Schema is the powerful refinement syntax.

Api reference

ValidationResult

ValidationResult represents the result of a validation. It containes the following fields:

  • errors: a list of ValidationError if validation fails
  • value: an instance of type if validation succeded
// the definition of `ValidationError`
var ValidationError = t.struct({
  message: t.String,                        // a default message for developers
  actual: t.Any,                            // the actual value being validated
  expected: t.Function,                     // the type expected
  path: list(t.union([t.String, t.Number])) // the path of the value
}, 'ValidationError');

// the definition of `ValidationResult`
var ValidationResult = t.struct({
  errors: list(ValidationError),
  value: t.Any
}, 'ValidationResult');

#isValid()

Returns true if there are no errors.

validate('a', t.String).isValid(); // => true

#firstError()

Returns an object that contains an error message or null if validation succeeded.

validate(1, t.String).firstError().message; // => 'value is `1`, should be a `Str`'

validate(value, type, [options]) -> ValidationResult

  • value the value to validate
  • type a type defined with the tcomb library
  • options (optional) is an object with the following keys
    • path: Array<string | number> path prefix for validation
    • context: any passed to getValidationErrorMessage (useful for i18n)
    • strict: boolean (default false) if true no additional properties are allowed while validating structs

Tests

Run npm test

License

The MIT License (MIT)

More Repositories

1

fp-ts

Functional programming in TypeScript
TypeScript
10,811
star
2

io-ts

Runtime type system for IO decoding/encoding
TypeScript
6,694
star
3

tcomb-form-native

Forms library for react-native
JavaScript
3,148
star
4

tcomb

Type checking and DDD for JavaScript
JavaScript
1,897
star
5

tcomb-form

Forms library for react
JavaScript
1,163
star
6

monocle-ts

Functional optics: a (partial) porting of Scala monocle
TypeScript
1,001
star
7

newtype-ts

Implementation of newtypes in TypeScript
TypeScript
553
star
8

babel-plugin-tcomb

Babel plugin for static and runtime type checking using Flow and tcomb
JavaScript
482
star
9

flow-static-land

[DEPRECATED, please check out fp-ts] Implementation of common algebraic types in JavaScript + Flow
JavaScript
408
star
10

functional-programming

Introduction to Functional Programming (Italian)
TypeScript
401
star
11

typelevel-ts

Type level programming in TypeScript
TypeScript
354
star
12

io-ts-types

A collection of codecs and combinators for use with io-ts
TypeScript
311
star
13

elm-ts

A porting to TypeScript featuring fp-ts, rxjs6 and React
TypeScript
301
star
14

redux-tcomb

Immutable and type-checked state and actions for Redux
JavaScript
211
star
15

tcomb-react

Alternative syntax for PropTypes
JavaScript
202
star
16

fp-ts-contrib

A community driven utility package for fp-ts
TypeScript
199
star
17

parser-ts

String parser combinators for TypeScript
TypeScript
194
star
18

fp-ts-rxjs

fp-ts bindings for RxJS
TypeScript
188
star
19

prop-types-ts

Alternative syntax for prop types providing both static and runtime type safety, powered by io-ts
TypeScript
170
star
20

fp-ts-routing

A type-safe bidirectional routing library for TypeScript
TypeScript
168
star
21

retry-ts

Retry combinators for monadic actions that may fail
TypeScript
162
star
22

io-ts-codegen

Code generation for io-ts
TypeScript
152
star
23

tcomb-json-schema

Transforms a JSON Schema to a tcomb type
JavaScript
144
star
24

flowcheck

[DEPRECATED, use babel-plugin-tcomb instead] Runtime type checking for Flow
JavaScript
116
star
25

fp-ts-codegen

TypeScript code generation from a haskell-like syntax for ADT. Playground:
TypeScript
101
star
26

docs-ts

A zero-config documentation tool for my TypeScript projects
TypeScript
100
star
27

logging-ts

Composable loggers for TypeScript
TypeScript
99
star
28

flowcheck-loader

[DEPRECATED] A Webpack loader for Flowcheck
JavaScript
89
star
29

tom

Elmish type-safe state and side effect manager using RxJS
JavaScript
87
star
30

money-ts

TypeScript library for type-safe and lossless encoding and manipulation of world currencies and precious metals
TypeScript
87
star
31

fp-ts-laws

fp-ts type class laws for property based testing
TypeScript
80
star
32

flow-io

[DEPRECATED, please check out io-ts] Flow compatible runtime type system for IO validation
JavaScript
73
star
33

react-vdom

Pulls out the VDOM and makes tests easy (also in node and without the DOM)
JavaScript
72
star
34

uvdom

Universal Virtual DOM
JavaScript
53
star
35

fp-ts-fluture

fp-ts bindings for Fluture
TypeScript
50
star
36

fp-ts-local-storage

fp-ts bindings for LocalStorage
TypeScript
49
star
37

graphics-ts

A porting of purescript-{canvas, drawing} featuring fp-ts
TypeScript
44
star
38

tcomb-react-bootstrap

Type checking for react-bootstrap [DEPRECATED]
JavaScript
41
star
39

talks

talks and blog posts
HTML
41
star
40

unknown-ts

A polyfill of unknown that works with legacy typescript versions (before 3.0)
TypeScript
28
star
41

mtl-ts

MTL-style in TypeScript
TypeScript
24
star
42

recursion-schemes-ts

Recursion schemes in TypeScript (POC)
TypeScript
22
star
43

tcomb-doc

Documentation tool for tcomb
JavaScript
14
star
44

babel-plugin-tcomb-boilerplate

Boilerplate showing what you can get in terms of type safety with babel-plugin-tcomb
JavaScript
14
star
45

fp-ts-node

TypeScript
13
star
46

flow-react

Advanced type checking for react using Flow
JavaScript
13
star
47

pantarei

Repository for idiomatic Flowtype definition files
JavaScript
11
star
48

elm-ts-todomvc

todomvc implementation using elm-ts and fp-ts
TypeScript
11
star
49

typescript-course

Esercizi del corso di programmazione avanzata con TypeScript
TeX
11
star
50

tcomb-form-templates-semantic

Semantic UI templates for tcomb-form
JavaScript
11
star
51

tcomb-form-templates-bootstrap

Bootstrap templates for tcomb-form
JavaScript
10
star
52

sanctuary-libdef

Flow definition file for sanctuary
JavaScript
9
star
53

simple-date-picker

A simple clean way to pick dates with React
JavaScript
9
star
54

flow-update

Statically type checked model updates using Flow
JavaScript
8
star
55

profunctor-lenses-ts

Pure profunctor lenses in TypeScript (just a POC)
TypeScript
8
star
56

fp-typed-install

TypeScript
7
star
57

cerebral-tcomb

[No Maintenance Intended] immutable and type checked model layer for cerebral
JavaScript
7
star
58

import-path-rewrite

JavaScript
6
star
59

fractal-trees-ts

Fractal trees with fp-ts
TypeScript
6
star
60

fcomb

Function combinators
JavaScript
5
star
61

uvdom-bootstrap

Bootstrap 3 components built with uvdom
JavaScript
5
star
62

simple-format-number

A simple clean way to format numbers with Javascript
JavaScript
5
star
63

behaviors-ts

A porting of purescript-behaviors
TypeScript
5
star
64

tree-shaking-test

JavaScript
4
star
65

io-ts-benchmarks

TypeScript
3
star
66

fetch-optimizer

[No Maintenance Intended] Optimises dependent data fetchers
JavaScript
2
star
67

simple-format-timeago

A simple clean way to format intervals with Javascript
JavaScript
2
star
68

simple-format-date

A simple clean way to format dates with Javascript
JavaScript
2
star
69

tcomb-i18n

Simple i18n / i17n helpers [DEPRECATED]
JavaScript
2
star
70

simple-parse-number

A simple clean way to parse numbers with Javascript
JavaScript
1
star