0.5.2 • Published 6 years ago

flash-validate v0.5.2

Weekly downloads
-
License
MIT
Repository
-
Last release
6 years ago

Key features

  • Very fast (faster than fastest-validator)
  • As good as a hand-coded validation function!
  • Nested object & array handling
  • Multiple validators
  • Customizable error messages (coming soon)
  • Programmable error object (coming soon)
  • No dependencies
  • Unit tests & near 100% cover

How fast?

About 2.5 times faster than fastest-validator in it's simple benchmark. For more complex structures with nested objects and values it should be about 1.5 to 2 times faster than fastest-validator. In any case, many thanks to fastest-validator for it served as the basis for this project!

Platform info:
==============
   Darwin 17.2.0 x64
   Node.JS: 9.5.0
   V8: 6.2.414.46-node.18
   Intel(R) Core(TM) i7-4850HQ CPU @ 2.30GHz × 8

Suite: Simple object
✔ compile & validate                        7,377,252 rps
✔ validate with pre-compiled schema         8,744,150 rps
✔ validate with wrong obj                   8,356,860 rps

Installation

You can install it via NPM.

$ npm install flash-validate --save

or

$ yarn add flash-validate

Usage

There are two ways to use flash-validate: the simple method and the fast method.

Simple method

Call the validate method with the object and the schema.

If the performance is important, you should pre-compile the schema first.

const Validator = require("flash-validate"),
      v = new Validator()

const schema = {
    id: { type: "number", positive: true, integer: true },
    name: { type: "string", min: 3, max: 255 },
    status: "boolean"
}

console.log(v.validate({ id: 5, name: "John", status: true }, schema))
// Outputs: true

console.log(v.validate({ id: 5, name: "Al", status: true }, schema))
/* Outputs an error object:
    { 
        type: 'stringMin',
        expected: 3,
        actual: 2,
        field: 'name',
        message: 'The \'name\' field length must be larger than or equal to 3 characters long!'
    }
*/

Fast method

We begin by compiling the schema into a native function, which can be then be used without the schema argument.

You gain about 20% performance this way.

const Validator = require("fastest-validator"),
      v = new Validator()

const schema = {
    id: { type: "number", positive: true, integer: true },
    name: { type: "string", min: 3, max: 255 },
    status: "boolean"
}

var validate = v.compile(schema);

console.log(validate({ id: 5, name: "John", status: true }));
// Outputs: true

console.log(validate({ id: 2, name: "Adam" }));
/* Outputs an error object::
    { 
        type: 'required',
        field: 'status',
        message: 'The \'status\' field is required!'
    }
*/

Optional & required fields

Every fields in the schema will be required field. If you would like to define optional fields, set optional: true.

let schema = {
    name: { type: "string" }, // required
    age: { type: "number", optional: true }
}

v.validate({ name: "John", age: 42 }, schema); // Valid
v.validate({ name: "John" }, schema); // Valid
v.validate({ age: 42 }, schema); // Fail

Multiple validators

It's possible to multiple validators for a field. If any of the schemas validates, the field will validate.

let schema = {
    cache: [
        { type: "string" },
        { type: "boolean" }
    ]
}

v.validate({ cache: true }, schema); // Valid
v.validate({ cache: "redis://" }, schema); // Valid
v.validate({ cache: 150 }, schema); // Fail

Built-in validators

any

This is not validate the type of value. Accept any types.

let schema = {
    prop: { type: "any" }
}

v.validate({ prop: true }, schema); // Valid
v.validate({ prop: 100 }, schema); // Valid
v.validate({ prop: "John" }, schema); // Valid

array

This is an Array validator.

Simple example with strings:

let schema = {
    roles: { type: "array", items: "string" }
}

v.validate({ roles: ["user"] }, schema); // Valid
v.validate({ roles: [] }, schema); // Valid
v.validate({ roles: "user" }, schema); // Fail

Example with only positive number:

let schema = {
    list: { type: "array", min: 2, items: {
        type: "number", positive: true, integer: true
    } }
}

v.validate({ list: [2, 4] }, schema); // Valid
v.validate({ list: [1, 5, 8] }, schema); // Valid
v.validate({ list: [1] }, schema); // Fail (min 2 elements)
v.validate({ list: [1, -7] }, schema); // Fail (negative number)

Example with object list:

let schema = {
    users: { type: "array", items: {
        type: "object", props: {
            id: { type: "number", positive: true },
            name: { type: "string", empty: false },
            status: "boolean"
        }
    } }
}

v.validate({ 
    users: [
        { id: 1, name: "John", status: true },
        { id: 2, name: "Jane", status: true },
        { id: 3, name: "Bill", status: false }
    ]
}, schema); // Valid

Properties

PropertyDefaultDescription
emptyfalseIf false, the validator will not accepts an empty array [].
minnullMinimum count of elements.
maxnullMaximum count of elements.
lengthnullFix count of elements.
containsnullThe array must contains this element too.
enumnullEvery element must be an element of the enum array.

Example for enum:

let schema = {
    roles: { type: "array", items: "string", enum: [ "user", "admin" ] }
}

v.validate({ roles: ["user"] }, schema); // Valid
v.validate({ roles: ["user", "admin"] }, schema); // Valid
v.validate({ roles: ["guest"] }, schema); // Fail

boolean

This is a Boolean validator.

let schema = {
    status: { type: "boolean" }
}

v.validate({ status: true }, schema); // Valid
v.validate({ status: false }, schema); // Valid
v.validate({ status: 1 }, schema); // Fail
v.validate({ status: "true" }, schema); // Fail

Properties

PropertyDefaultDescription
convertfalseif true and the type is not Boolean, try to convert. 1, "true", "1", "on" will be true. 0, "false", "0", "off" will be false.

date

This is a Date validator.

let schema = {
    dob: { type: "date" }
}

v.validate({ dob: new Date() }, schema); // Valid
v.validate({ dob: new Date(1488876927958) }, schema); // Valid
v.validate({ dob: 1488876927958 }, schema); // Fail

Properties

PropertyDefaultDescription
convertfalseif true and the type is not Date, try to convert with new Date().

email

This is an e-mail address validator.

let schema = {
    email: { type: "email" }
}

v.validate({ email: "john.doe@gmail.com" }, schema); // Valid
v.validate({ email: "james.123.45@mail.co.uk" }, schema); // Valid
v.validate({ email: "abc@gmail" }, schema); // Fail

Properties

PropertyDefaultDescription
modequickChecker method. Can be quick or precise.

forbidden

This validator gives error if the property is exists in the object.

let schema = {
    password: { type: "forbidden" }
}

v.validate({ user: "John" }, schema); // Valid
v.validate({ user: "John", password: "pass1234" }, schema); // Fail

function

The type of value must be Function.

let schema = {
    show: { type: "function" }
}

v.validate({ show: function() {} }, schema); // Valid
v.validate({ show: Date.now }, schema); // Valid
v.validate({ show: null }, schema); // Fail

number

This is a number validator. The type of value must be Number.

let schema = {
    age: { type: "number" }
}

v.validate({ age: 123 }, schema); // Valid
v.validate({ age: 5.65 }, schema); // Valid
v.validate({ age: "100" }, schema); // Fail

Properties

PropertyDefaultDescription
minnullMinimum value.
maxnullMaximum value.
equalnullFix value.
notEqualnullCan't be equal with this value.
integerfalseThe value must be a non-decimal value.
positivefalseThe value must be larger than zero.
negativefalseThe value must be less than zero.
convertfalseif true and the type is not Number, try to convert with parseFloat.

object

This is a nested object validator.

let schema = {
    address: { type: "object", props: {
        country: { type: "string" },
        city: "string", // short-hand
        zip: "number" // short-hand
    } }
}

v.validate({ 
    address: {
        country: "Italy",
        city: "Rome",
        zip: 12345
    } 
}, schema); // Valid

v.validate({ 
    address: {
        country: "Italy",
        city: "Rome"
    }
}, schema); // Fail ("The 'address.zip' field is required!")

string

This is a string validator. The type of value must be String.

let schema = {
    name: { type: "string" }
}

v.validate({ name: "John" }, schema); // Valid
v.validate({ name: "" }, schema); // Valid
v.validate({ name: 123 }, schema); // Fail

Properties

PropertyDefaultDescription
emptytrueIf true, the validator accepts empty string "".
minnullMinimum length of value.
maxnullMaximum length of value.
lengthnullFix length of value.
patternnullRegex pattern.
containsnullThe value must contains this text.
enumnullThe value must be an element of the enum array.

url

This is an URL validator.

let schema = {
    url: { type: "url" }
}

v.validate({ url: "http://google.com" }, schema); // Valid
v.validate({ url: "https://github.com/icebob" }, schema); // Valid
v.validate({ url: "www.facebook.com" }, schema); // Fail

Message types

flash-validate uses the same message structure as fastest-validator.

NameDefault text
requiredThe '{field}' field is required!
stringThe '{field}' field must be a string!
stringEmptyThe '{field}' field must not be empty!
stringMinThe '{field}' field length must be larger than or equal to {expected} characters long!
stringMaxThe '{field}' field length must be less than or equal to {expected} characters long!
stringLengthThe '{field}' field length must be {expected} characters long!
stringPatternThe '{field}' field fails to match the required pattern!
stringContainsThe '{field}' field must contain the '{expected}' text!
stringEnumThe '{field}' field does not match any of the allowed values!
numberThe '{field}' field must be a number!
numberMinThe '{field}' field must be larger than or equal to {expected}!
numberMaxThe '{field}' field must be less than or equal to {expected}!
numberEqualThe '{field}' field must be equal with {expected}!
numberNotEqualThe '{field}' field can't be equal with {expected}!
numberIntegerThe '{field}' field must be an integer!
numberPositiveThe '{field}' field must be a positive number!
numberNegativeThe '{field}' field must be a negative number!
arrayThe '{field}' field must be an array!
arrayEmptyThe '{field}' field must not be an empty array!
arrayMinThe '{field}' field must contain at least {expected} items!
arrayMaxThe '{field}' field must contain less than or equal to {expected} items!
arrayLengthThe '{field}' field must contain {expected} items!
arrayContainsThe '{field}' field must contain the '{expected}' item!
arrayEnumThe '{field} field value '{expected}' does not match any of the allowed values!
booleanThe '{field}' field must be a boolean!
functionThe '{field}' field must be a function!
dateThe '{field}' field must be a Date!
dateMinThe '{field}' field must be larger than or equal to {expected}!
dateMaxThe '{field}' field must be less than or equal to {expected}!
forbiddenThe '{field}' field is forbidden!
emailThe '{field}' field must be a valid e-mail!

Message fields

NameDescription
fieldName of field
expectedThe expected value of field
actualThe actual value of field
typeType of field

Coverage report

-----------------|----------|----------|----------|----------|-------------------|
File             |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files        |    95.47 |    93.42 |    96.77 |    95.34 |                   |
 lib             |    85.25 |    78.13 |    90.91 |    84.21 |                   |
  assembler.js   |    85.25 |    78.13 |    90.91 |    84.21 |... 11,112,113,122 |
 lib/generators  |     98.9 |     97.5 |      100 |    98.88 |                   |
  alternative.js |    88.24 |    66.67 |      100 |     87.5 |             48,51 |
  any.js         |      100 |      100 |      100 |      100 |                   |
  array.js       |      100 |    97.06 |      100 |      100 |               100 |
  boolean.js     |      100 |      100 |      100 |      100 |                   |
  date.js        |      100 |      100 |      100 |      100 |                   |
  email.js       |      100 |      100 |      100 |      100 |                   |
  forbidden.js   |      100 |      100 |      100 |      100 |                   |
  function.js    |      100 |      100 |      100 |      100 |                   |
  number.js      |      100 |      100 |      100 |      100 |                   |
  object.js      |      100 |      100 |      100 |      100 |                   |
  optional.js    |      100 |      100 |      100 |      100 |                   |
  string.js      |      100 |      100 |      100 |      100 |                   |
  url.js         |      100 |      100 |      100 |      100 |                   |
-----------------|----------|----------|----------|----------|-------------------|

Thanks

Many thanks to fastest-validator! Lot's of ideas were for this project were directly taken from there.

Contribution

Please send pull requests improving the usage and fixing bugs, improving documentation and providing better examples, or providing some testing, because these things are important.

License

flash-validate is available under the MIT license.