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
:
-> ValidationResult
value
the value to validatetype
a type defined with the tcomb libraryoptions
(optional) is an object with the following keyspath: Array<string | number>
path prefix for validationcontext: any
passed togetValidationErrorMessage
(useful for i18n)strict: boolean
(defaultfalse
) iftrue
no additional properties are allowed while validating structs
returns a ValidationResult
object containing the result of the validation
Note.
options
can be an array (aspath
prefix) for backward compatibility (deprecated)
Example
var t = ;var validate = tvalidate; ; // => false; // => true
You can inspect the result to quickly identify what's wrong:
var result = ;result; // => falseresultmessage; // => 'Invalid value 1 supplied to String' // see `result.errors` to inspect all errors
Primitives
// null and undefined; // => false; // => true; // => true // strings; // => false; // => true // numbers; // => false; // => true // booleans; // => false; // => true // optional values; // => true; // => true; // => false // functions; // => false; // => true // dates; // => false; // => true // regexps; // => false; // => true
Refinements
You can express more fine-grained contraints with the refinement
syntax:
// a predicate is a function with signature: (x) -> booleanvar { return x >= 0; }; // a positive numbervar Positive = t; ; // => false; // => true
Objects
Structs
// an object with two numerical propertiesvar Point = t; ; // => false; // => false, y is missing; // => false, y is not a number; // => true; // => false, no additional properties are allowed
Interfaces
Differences from structs
- also checks prototype keys
var Serializable = t; ; // => false Pointprototype { ... } ; // => true
Lists and tuples
Lists
// a list of stringsvar Words = t; ; // => false; // => false, [1] is not a string; // => true
Tuples
// a tuple (width x height)var Size = t; ; // => false, height missing; // => false, bad height; // => true
Enums
var CssTextAlign = tenums; ; // => false; // => true
Unions
var CssLineHeight = t; ; // => false; // => true; // => true
Dicts
// a dictionary of numbersvar Country = tenums;var Warranty = t; ; // => false; // => false, ['a'] is not a Country; // => false, ['IT'] is not a number; // => true
Intersections
var Min = t;var Max = t;var MinMax = t; MinMax; // => trueMinMax; // => falseMinMax; // => false
Nested structures
You can validate structures with an arbitrary level of nesting:
var Post = t; var mypost = title: 'Awesome!' content: 'You can validate structures with arbitrary level of nesting' tags: 'validation' 1 // <-- ouch!; ; // => falsemessage; // => '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; ShortString { if !value return 'Required'; if valuelength >= 3 return 'Too long my friend'; }; 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:
{ var Subtype = t; SubtypegetValidationErrorMessage = getValidationErrorMessage; return Subtype;} var ShortString = ;
Use cases
Form validation
Let's design the process for a simple sign in form:
var SignInInfo = t; // retrieves values from the UIvar formValues = username: || null password: || null; // if formValues = {username: null, password: 'password'}var result = ;result; // => falseresultmessage; // => '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/
and the equivalent tcomb-validation
counterpart:
var Schema = t;
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"; ; // => 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 ofValidationError
if validation failsvalue
: an instance oftype
if validation succeded
// the definition of `ValidationError`var ValidationError = t; // the definition of `ValidationResult`var ValidationResult = t;
#isValid()
Returns true if there are no errors.
; // => true
#firstError()
Returns an object that contains an error message or null
if validation succeeded.
message; // => 'value is `1`, should be a `Str`'
validate(value, type, [options]) -> ValidationResult
value
the value to validatetype
a type defined with the tcomb libraryoptions
(optional) is an object with the following keyspath: Array<string | number>
path prefix for validationcontext: any
passed togetValidationErrorMessage
(useful for i18n)strict: boolean
(defaultfalse
) iftrue
no additional properties are allowed while validating structs
Tests
Run npm test
License
The MIT License (MIT)