Skip to content

documentation

Bruno Dias edited this page Aug 27, 2019 · 6 revisions

about

this package contains a implementation of a data validation in a functional lisp-like style.

it's intended to be dependency-free, reusable and with a simple api.

api

all checkers have the following api:

basic validation:

Checker = (b: any, smsg: any, merge: Function);

T = (f: Function, msg: any) => Checker;

all other validation and combinators:

ifFail    = (checker: T, emsg: any) => Checker;
all       = (...args: [T]) => Checker;
or        = (...args: [T]) => Checker;
object    = (obj: Object[String, T]) => Checker;
ordobject = (arr: [key: String, checker: T, ...args]) => Checker;

where

  • f is a simple function or a checker
  • msg can be anything for the error message
  • b is any value to be tested
  • smsg can be anything for the success message
  • merge is a function that knows how to combine the results

example

> const greaterThanOne = T(b => b > 1, 'less than one');
> const lessThanOne = T(b => b < 1, 'greater than one');

> greaterThanOne(0);
// { msg: 'less than one', result: false } 

> greaterThanOne(2, 'ok');
// { msg: 'ok', result: true} 

write the way is more suitable for your application

const isString = T(b => b.constructor == String, 'not a string');
const noSpaces = T(b => !/\s/g.test(b), 'should not contains spaces');
const noMoreThan = a => T(b => b.length <= a, `should not be longer than ${a} characters`);

const validate = all(isString, noSpaces, noMoreThan(5));

validate(1, "is valid");
validate("javascript", "is valid");
validate("car", "is valid");

// ...or

const isValidName = T(b => b.constructor == String && 
                           !/\s/g.test(b) && 
                           b.length <= 5, 'not a valid name');
isValidName("javascript", "is valid");
Clone this wiki locally