is-validation

Input validation and manipulation library

is-validation

Library for chaining validation and manipulation together

It provides a convienient way of validating and converting input while providing easy to read and informative error messages.

 
var is = require('is');
 
// static validation usage 
is.number(123);
// true 
is.lessThan(123, 100);
// false 
 
// simple chaining 
is(123)
  .number()
  .lessThan(100)
;
 
is.valid;
// false 
is.errorCount;
// 1 
is.testCount;
// 2 
 
// complex chaining 
var chain = is("hello world");
chain
  .string()
  .property('length')
    .greaterThan(10)
    .lessThan(20)
    .up() // go back to parent chain 
  .match(/^[a-z ]+$/i)
;
 
chain.valid;
// true 
is.valid;
// false (still false from simple chaining example) 
 
chain.errorCount;
// 0 
is.errorCount;
// 1 
 
chain.testCount;
// 4 
is.testCount;
// 6 
 
is.clear();
 
is.valid;
// true 
is.testCount;
// 0 
is.errorCount;
// 0 
 
$ npm install is-validation

Registers a new Chain to is

  • val - The subject of the chain
  • name - The name to be used in error messages

returns a new Chain instance

returns is

 
is.a.string('abc');
// true 
 
is === is.a.an;
// true 
 

Returns false if any registered Chain has any errors

Returns the total number of tests of all registered Chains

Returns the total number of errors of all registered Chains

Returns an array of error messages from all registered Chains

Clears out all registered Chains

returns is

If is.valid is false, throw is.errorMessages as an Exception

Add a validator to is and the Chain prototype

  • name - The name the validator may be accessed through
  • fn - The validation function. Returns true on valid, false on not valid
  • options
    • failMessage - The error message for if the validation fails (default: 'pass ' + name + ' test')
 
is.configure.addValidator('odd', function (val) {
    return val % 2 === 1;
}, { failMessage: 'be odd' });
 
is.odd(3);
// true 
 
is(2).odd().errorMessage;
// 'value must be odd' 
 

Add a manipulator to is and the Chain prototype

  • name - The name the manipulator may be access through
  • fn - The manipulation function. Returns the manipulated value
  • options
    • failVal - A value or function to compare to the manipulated value to indicate failure. If not set, the manipulation cannot fail
    • failMessage - The error message for if the manipulation fails (default: 'be able to be manipulated by ' + name)
 
is.configure.addManipulator('toExponent', function (valexp) {
    return Math.pow(val, exp);
}, { failVal: isNaN, failMessage: 'be a number' });
 
is.toExponent(5, 2);
// 25 
 
is('abc').toExponent(2).errorMessage;
// 'value must be a number' 
 

All validation and manipulation methods are available as properties of is.

 
is.string('abc');
// true 
 
is.lessThan(123, 100);
// false 
 

returns this

Negates the next test

returns this

 
is('abc').not.a.number().valid;
// true 
 

Simple or condition

If the validation before .or or the validation after passes, then the chain is considered valid

 
is(123)
  .a.string().or
    .a.number()
  .valid;
// true 
 
is(123)
  .a.string().or
    .an.array().or
    .a.regExp()
  .errorMessage;
// 'value must be a string, be an array, or be a regular expression' 
 

The behavior of or may be a little strange, and I am open to suggestions:

  • All or tests after a valid test will be skipped
  • All errors in a set of ors count as 1 error in .errorCount
  • Only the tests that are performed until a valid test count towards .testCount (I might set all or tests to count as 1)
  • There is no grouping of tests (yet - let me know if this is desired). or will only work with single tests

Returns the manipulated subject of the Chain

Returns true if no errors have occured on the chain

Returns the number of tests that have occured on the chain

Returns the number of errors that have occured on the chain

Returns a composed error message describing all the tests that have failed on the chain

Clears out all tests on the chain

returns this

Creates a new Chain with the current chains property propName as the subject

  • propName - the property to use as the new subject
  • name - the name to be used in the error message. (default: propName)
 
is('abc')
  .a.string()
  .property('length', 'total number of characters')
    .greaterThan(5)
    .lessThan(10)
    .up()
  .errorMessage;
// 'value must have a total number of characters which must be greater than 5' 
 

Starts bypassing validations and manipulations if the chain is not valid

Starts bypassing validations and manipulations on the chain

Stops bypassing validations and manipulations on the chain

Returns the parent chain if it exists

 
var chain = is('abc')
  , length = chain.property('length')
;
 
chain === length;
// false 
 
chain === length.up();
// true 
 

Throws an exception if the chain is not valid

Run a one time validation in the chain

  • fn - The validation function. Returns true on success, false on failure
  • failMessage - The error message if the validation fails
 
is(123)
  .validate(function (val) {
      return val % 2 === 0;
  }, 'be even')
  .errorMessage;
// 'value must be even' 
 

Run a one time manipulation in the chain

  • fn - The manipulation function. Returns the manipulated value
  • name - The name of the manipulated value

returns this

 
is(123)
  .manipulate(function (val) {
      return val * val;
  }, 'value squared')
    .value;
// 15129 
 

Replace the chains error format with format

  • format - a string to represent how error messages are displayed

The default format is '{0} must {1}' where {0} is the name of the chain subject and {1} is the list of error messages

Replace the chain property format with format

  • format - a string to represent how properties are formatted in error messages

The default format is 'have a {0} which must {1}' where {0} is the name of the property and {1} is the list of error messages for the property

Error messages are customizable and more informative than simply stating 'invalid input'

 
is('$ab', 'Your username')
  .string()
  .match(/^[a-z]*$/i, 'only be alphabetic characters')  // fails 
  .property('length')
    .greaterThan(5)  // fails 
    .lessThan(15)
;
 
is.errorMessages;
// ['Your username must only be alphabetic characters and have a length which must be greater than 5'] 
 

Is val a string object

Is val numeric. NaN, Infinity, true, false, and '' are not numeric

Is val a number object

Simple less than comparison: return val < limit

Simple less than or equal comparison: return val <= limit

Simple greater than comparison: return val > limit

Simple greater than or equal comparison: return val > limit

Exclusive comparison: return val > lower && val < upper

Inclusive comparison: return val >= lower && val <= upper

Uses deep-is to compare objects

Simple strict equality comparison: return val === expected

val must equal true or false

Can val be parsed into a date

Is val a Date object

Is val an object

Check if val is an object literal

{} - true new Object() - true [] - false new Date() - false

Check for the existance of val in an array or string

Does val have a property propName

Does val have its own property propNam

Compares val to a regular expression

Is val a function

Is val an arguments object

Is val a regular expression

Is val an instance of constructor

Is val an array

Is val a Buffer object

Is val empty

  • array, arguments, and string - true if val.length === 0
  • null, undefined - true
  • object - true if it has no properties of its own

Returns a string representation of val

  • undefined and null - returns an empty string ('')
  • object literal - returns JSON.stringify(val)
  • everything else - returns String(val)

Cannot fail

Trims characters from both side of val. It will convert val to a string using is.toString

  • chars - the characters to trim from the sides (default: '\r\n\t\s' - whitespace characters)

Cannot fail

Trims characters from the left side of val. It will convert val to a string using is.toString

  • chars - the characters to trim from the left side (default: '\r\n\t\s' - whitespace characters)

Cannot fail

Trims characters from the right side of val. It will convert val to a string using is.toString

  • chars - the characters to trim from the right side (default: '\r\n\t\s' - whitespace characters)

Cannot fail

Parse val into a number

An empty string ('') returns NaN. Everything else is parsed by Number(val)

  • failVal - isNaN
  • failMessage - 'be a number'

Use parseInt to parse val

  • radix - the radix to use in parseInt (default: 10)

  • failVal - isNaN

  • failMessage - 'be an integer'

Use parseFloat to parse val

  • failVal - isNaN
  • failMessage - 'be a floating point number'

Converts val into true or false

'', '0', 'false', and falsy objects will be converted to false. Everything else will be true.

Cannot fail

Converts val into a Date object

null, undefined, and boolean values return NaN

  • failVal - isNaN
  • failMessage - 'be a valid date'

Converts val into a regular expression

It will convert RegExp.toString() back into a RegExp. All other strings will not have flags

 
var reg = /^hello$/gi
  , str = reg.toString() // '/^hello$/gi' 
;
 
is.toRegExp(str);
// /^hello$/gi 
 
is.toRegExp('^helloE');
// /^hello$/ 
 
  • failVal - null
  • failMessage - 'be a regular expression'

Replaces val with newVal if it equals compare

compare may also be a function which returns true to replace the values

 
is.default('abc', 'def', 'abc');
// 'def' 
 
is.default(123, 0, isNaN);
// 123 
 
is.default(undefined, '') // `compare` is undefined. Its value is `undefined` 
// '' 
 
is('abc')
  .toNumber()        // converts 'abc' to NaN 
  .default(0, isNaN) // replaces NaN with 0 
  .clear()           // clear out errors from `toNumber()` 
  .value;              // return the value 
// 0 
 

Cannot fail

  • This library is brand new and still under development. The API is still changing.
  • Type-checking will not work across multiple frames or through REPL. I chose not to use the slower Object.prototype.toString method of type checking.
  • All validation and manipulation methods must be synchronous