fastest-validator

The fastest JS validator library for NodeJS

README

Photos from @ikukevk

Node CI Coverage Status Codacy Badge Known Vulnerabilities Size

fastest-validator NPM version Tweet

:zap: The fastest JS validator library for NodeJS | Browser | Deno.

Key features

blazing fast! Really!
20+ built-in validators
many sanitizations
custom validators & aliases
nested objects & array handling
strict object validation
multiple validators
customizable error messages
programmable error object
no dependencies
unit tests & 100% coverage

How fast?

Very fast! 8 million validations/sec (on Intel i7-4770K, Node.JS: 12.14.1)
  1. ```
  2. validate                            8,678,752 rps
  3. ```

Compared to other popular libraries:
Result

50x faster than Joi.


Would you like to test it?

  1. ```
  2. $ git clone https://github.com/icebob/fastest-validator.git
  3. $ cd fastest-validator
  4. $ npm install
  5. $ npm run bench
  6. ```

Approach

In order to achieve lowest cost/highest performance redaction fastest-validator creates and compiles functions using the Function constructor. It's important to distinguish this from the dangers of a runtime eval, no user input is involved in creating the validation schema that compiles into the function. This is as safe as writing code normally and having it compiled by V8 in the usual way.

Installation


NPM

You can install it via NPM.
  1. ```
  2. $ npm i fastest-validator --save
  3. ```
or
  1. ```
  2. $ yarn add fastest-validator
  3. ```

Usage


Validate

The first step is to compile the schema to a compiled "checker" function. After that, to validate your object, just call this "checker" function.

This method is the fastest.


  1. ``` js
  2. const Validator = require("fastest-validator");

  3. const v = new Validator();

  4. const schema = {
  5.     id: { type: "number", positive: true, integer: true },
  6.     name: { type: "string", min: 3, max: 255 },
  7.     status: "boolean" // short-hand def
  8. };

  9. const check = v.compile(schema);

  10. console.log("First:", check({ id: 5, name: "John", status: true }));
  11. // Returns: true

  12. console.log("Second:", check({ id: 2, name: "Adam" }));
  13. /* Returns an array with errors:
  14.     [
  15.         {
  16.             type: 'required',
  17.             field: 'status',
  18.             message: 'The \'status\' field is required!'
  19.         }
  20.     ]
  21. */
  22. ```

Halting


If you want to halt immediately after the first error:
  1. ``` js
  2. const v = new Validator({ haltOnFirstError: true });
  3. ```

Browser usage

  1. ``` html
  2. <script src="https://unpkg.com/fastest-validator"></script>
  3. ```

  1. ``` js
  2. const v = new FastestValidator();

  3. const schema = {
  4.     id: { type: "number", positive: true, integer: true },
  5.     name: { type: "string", min: 3, max: 255 },
  6.     status: "boolean" // short-hand def
  7. };

  8. const check = v.compile(schema);

  9. console.log(check({ id: 5, name: "John", status: true }));
  10. // Returns: true
  11. ```

Deno usage

With esm.sh, now Typescript is supported

  1. ``` js
  2. import FastestValidator from "https://esm.sh/fastest-validator@1"

  3. const v = new FastestValidator();
  4. const check = v.compile({
  5.     name: "string",
  6.     age: "number",
  7. });

  8. console.log(check({ name: "Erf", age: 18 })); //true
  9. ```

Supported frameworks

- Moleculer: Natively supported
- Fastify: By using fastify-fv
- Express: By using fastest-express-validator

Optional, Required & Nullable fields

Optional

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

  1. ``` js
  2. const schema = {
  3.     name: { type: "string" }, // required
  4.     age: { type: "number", optional: true }
  5. }

  6. const check = v.compile(schema);

  7. check({ name: "John", age: 42 }); // Valid
  8. check({ name: "John" }); // Valid
  9. check({ age: 42 }); // Fail because name is required
  10. ```

Nullable

If you want disallow undefined value but allow null value, use nullable instead of optional.
  1. ``` js
  2. const schema = {
  3.     age: { type: "number", nullable: true }
  4. }

  5. const check = v.compile(schema);

  6. check({ age: 42 }); // Valid
  7. check({ age: null }); // Valid
  8. check({ age: undefined }); // Fail because undefined is disallowed
  9. check({}); // Fail because undefined is disallowed
  10. ```

Nullable and default values

null is a valid input for nullable fields that has default value.

  1. ``` js
  2. const schema = {
  3.    about: { type: "string", nullable: true, default: "Hi! I'm using javascript" }
  4. }

  5. const check = v.compile(schema)

  6. const object1 = { about: undefined }
  7. check(object1) // Valid
  8. object1.about // is "Hi! I'm using javascript"

  9. const object2 = { about: null }
  10. check(object2) // valid
  11. object2.about // is null

  12. check({ about: "Custom" }) // Valid
  13. ```

Strict validation

Object properties which are not specified on the schema are ignored by default. If you set the $$strict option to true any additional properties will result in an strictObject error.

  1. ``` js
  2. const schema = {
  3.     name: { type: "string" }, // required
  4.     $$strict: true // no additional properties allowed
  5. }

  6. const check = v.compile(schema);

  7. check({ name: "John" }); // Valid
  8. check({ name: "John", age: 42 }); // Fail
  9. ```

Remove additional fields

To remove the additional fields in the object, set $$strict: "remove".

Multiple validators

It is possible to define more validators for a field. In this case, only one validator needs to succeed for the field to be valid.

  1. ``` js
  2. const schema = {
  3.     cache: [
  4.         { type: "string" },
  5.         { type: "boolean" }
  6.     ]
  7. }

  8. const check = v.compile(schema);

  9. check({ cache: true }); // Valid
  10. check({ cache: "redis://" }); // Valid
  11. check({ cache: 150 }); // Fail
  12. ```

Root element schema

Basically the validator expects that you want to validate a Javascript object. If you want others, you can define the root level schema, as well. In this case set the $$root: true property.

Example to validate a string variable instead of object
  1. ``` js
  2. const schema = {
  3.     $$root: true,
  4.     type: "string",
  5.     min: 3,
  6.     max: 6
  7. };

  8. const check = v.compile(schema);

  9. check("John"); // Valid
  10. check("Al"); // Fail, too short.
  11. ```

Sanitizations

The library contains several sanitizers. Please note, the sanitizers change the original checked object.

Default values

The most common sanitizer is the default property. With it, you can define a default value for all properties. If the property value is null* or undefined, the validator set the defined default value into the property.

Static Default value example:
  1. ``` js
  2. const schema = {
  3.     roles: { type: "array", items: "string", default: ["user"] },
  4.     status: { type: "boolean", default: true },
  5. };

  6. const check = v.compile(schema);

  7. const obj = {}

  8. check(obj); // Valid
  9. console.log(obj);
  10. /*
  11. {
  12.     roles: ["user"],
  13.     status: true
  14. }
  15. */
  16. ```
Dynamic Default value:
Also you can use dynamic default value by defining a function that returns a value. For example, in the following code, if createdAt field not defined in object`, the validator sets the current time into the property:

  1. ``` js
  2. const schema = {
  3.     createdAt: {
  4.         type: "date",
  5.         default: (schema, field, parent, context) => new Date()
  6.     }
  7. };

  8. const check = v.compile(schema);

  9. const obj = {}

  10. check(obj); // Valid
  11. console.log(obj);
  12. /*
  13. {
  14.     createdAt: Date(2020-07-25T13:17:41.052Z)
  15. }
  16. */
  17. ```

Shorthand definitions

You can use string-based shorthand validation definitions in the schema.

  1. ``` js
  2. const schema = {
  3.     password: "string|min:6",
  4.     age: "number|optional|integer|positive|min:0|max:99", // additional properties
  5.     state: ["boolean", "number|min:0|max:1"] // multiple types
  6. }
  7. ```

Array of X

  1. ``` js
  2. const schema = {
  3.     foo: "string[]" // means array of string
  4. }

  5. const check = v.compile(schema);

  6. check({ foo: ["bar"] }) // true
  7. ```

Nested objects


  1. ``` js
  2. const schema = {
  3.    dot: {
  4.       $$type: "object",
  5.       x: "number",  // object props here
  6.       y: "number",  // object props here
  7.    },
  8.    circle: {
  9.       $$type: "object|optional", // using other shorthands
  10.       o: {
  11.          $$type: "object",
  12.          x: "number",
  13.          y: "number",
  14.       },
  15.       r: "number"
  16.    }
  17. };
  18. ```

Alias definition

You can define custom aliases.

  1. ``` js
  2. v.alias('username', {
  3.     type: 'string',
  4.     min: 4,
  5.     max: 30
  6.     // ...
  7. });

  8. const schema = {
  9.     username: "username|max:100", // Using the 'username' alias
  10.     password: "string|min:6",
  11. }
  12. ```

Default options

You can set default rule options.

  1. ``` js
  2. const v = new FastestValidator({
  3.     defaults: {
  4.         object: {
  5.             strict: "remove"
  6.         }
  7.     }
  8. });
  9. ```

Label Option

You can use label names in error messages instead of property names.
  1. ``` js
  2. const schema = {
  3. email: { type: "email", label: "Email Address" },
  4. };
  5. const check = v.compile(schema);

  6. console.log(check({ email: "notAnEmail" }));

  7. /* Returns
  8. [
  9.   {
  10.     type: 'email',
  11.     message: "The 'Email Address' field must be a valid e-mail.",
  12.     field: 'email',
  13.     actual: 'notAnEmail',
  14.     label: 'Email Address'
  15.   }
  16. ]
  17. */
  18. ```

Built-in validators


any

This does not do type validation. Accepts any types.

  1. ``` js
  2. const schema = {
  3.     prop: { type: "any" }
  4. }

  5. const check = v.compile(schema)

  6. check({ prop: true }); // Valid
  7. check({ prop: 100 }); // Valid
  8. check({ prop: "John" }); // Valid
  9. ```

array

This is an Array validator.

Simple example with strings:
  1. ``` js
  2. const schema = {
  3.     roles: { type: "array", items: "string" }
  4. }
  5. const check = v.compile(schema)

  6. check({ roles: ["user"] }); // Valid
  7. check({ roles: [] }); // Valid
  8. check({ roles: "user" }); // Fail
  9. ```

Example with only positive numbers:
  1. ``` js
  2. const schema = {
  3.     list: { type: "array", min: 2, items: {
  4.         type: "number", positive: true, integer: true
  5.     } }
  6. }
  7. const check = v.compile(schema)

  8. check({ list: [2, 4] }); // Valid
  9. check({ list: [1, 5, 8] }); // Valid
  10. check({ list: [1] }); // Fail (min 2 elements)
  11. check({ list: [1, -7] }); // Fail (negative number)
  12. ```

Example with an object list:
  1. ``` js
  2. const schema = {
  3.     users: { type: "array", items: {
  4.         type: "object", props: {
  5.             id: { type: "number", positive: true },
  6.             name: { type: "string", empty: false },
  7.             status: "boolean"
  8.         }
  9.     } }
  10. }
  11. const check = v.compile(schema)

  12. check({
  13.     users: [
  14.         { id: 1, name: "John", status: true },
  15.         { id: 2, name: "Jane", status: true },
  16.         { id: 3, name: "Bill", status: false }
  17.     ]
  18. }); // Valid
  19. ```

Example for enum:
  1. ``` js
  2. const schema = {
  3.     roles: { type: "array", items: "string", enum: [ "user", "admin" ] }
  4. }

  5. const check = v.compile(schema)

  6. check({ roles: ["user"] }); // Valid
  7. check({ roles: ["user", "admin"] }); // Valid
  8. check({ roles: ["guest"] }); // Fail
  9. ```

Example for unique:
  1. ``` js
  2. const schema = {
  3.     roles: { type: "array", unique: true }
  4. }
  5. const check = v.compile(schema);

  6. check({ roles: ["user"] }); // Valid
  7. check({ roles: [{role:"user"},{role:"admin"},{role:"user"}] }); // Valid
  8. check({ roles: ["user", "admin", "user"] }); // Fail
  9. check({ roles: [1, 2, 1] }); // Fail
  10. ```

Properties

Property | Default  | Description
empty  | true   | If true, the validator accepts an empty array [].
min    | null   | Minimum count of elements.
max    | null   | Maximum count of elements.
length | null   | Fix count of elements.
contains | null | The array must contain this element too.
unique | null | The array must be unique (array of objects is always unique).
enum  | null   | Every element must be an element of the enum array.
items  | null   | Schema for array items.

boolean

This is a Boolean validator.

  1. ``` js
  2. const schema = {
  3.     status: { type: "boolean" }
  4. }
  5. const check = v.compile(schema);

  6. check({ status: true }); // Valid
  7. check({ status: false }); // Valid
  8. check({ status: 1 }); // Fail
  9. check({ status: "true" }); // Fail
  10. ```

Properties

Property | Default  | Description
convert | false | if true and the type is not Boolean, it will be converted. 1, "true", "1", "on" will be true. 0, "false", "0", "off" will be false. _It's a sanitizer, it will change the value in the original object._

Example for convert:
  1. ``` js
  2. const schema = {
  3.     status: { type: "boolean", convert: true}
  4. };

  5. const check = v.compile(schema);

  6. check({ status: "true" }); // Valid
  7. ```

class

This is a Class validator to check the value is an instance of a Class.

  1. ``` js
  2. const schema = {
  3.     rawData: { type: "class", instanceOf: Buffer }
  4. }
  5. const check = v.compile(schema);

  6. check({ rawData: Buffer.from([1, 2, 3]) }); // Valid
  7. check({ rawData: 100 }); // Fail
  8. ```

Properties

Property | Default  | Description
instanceOf | null | Checked Class.

currency

This is a Currency validator to check if the value is a valid currency string.

  1. ``` js
  2. const schema = {
  3.     money_amount: { type: "currency", currencySymbol: '$' }
  4. }
  5. const check = v.compile(schema);

  6. check({ money_amount: '$12.99'}); // Valid
  7. check({ money_amount: '$0.99'}); // Valid
  8. check({ money_amount: '$12,345.99'}); // Valid
  9. check({ money_amount: '$123,456.99'}); // Valid

  10. check({ money_amount: '$1234,567.99'}); // Fail
  11. check({ money_amount: '$1,23,456.99'}); // Fail
  12. check({ money_amount: '$12,34.5.99' }); // Fail
  13. ```

Properties

Property | Default  | Description
currencySymbol | null | The currency symbol expected in string (as prefix).
symbolOptional | false | Toggle to make the symbol optional in string, although, if present it would only allow the currencySymbol.
thousandSeparator | , | Thousand place separator character.
decimalSeparator | . | Decimal place character.
customRegex | null | Custom regular expression, to validate currency strings (For eg:  /[0-9]*/g).

date

This is a Date validator.

  1. ``` js
  2. const schema = {
  3.     dob: { type: "date" }
  4. }
  5. const check = v.compile(schema);

  6. check({ dob: new Date() }); // Valid
  7. check({ dob: new Date(1488876927958) }); // Valid
  8. check({ dob: 1488876927958 }); // Fail
  9. ```

Properties

Property | Default  | Description
convert  | false| if true and the type is not Date, try to convert with new Date(). _It's a sanitizer, it will change the value in the original object._

Example for convert:
  1. ``` js
  2. const schema = {
  3.     dob: { type: "date", convert: true}
  4. };

  5. const check = v.compile(schema);

  6. check({ dob: 1488876927958 }, ); // Valid
  7. ```

email

This is an e-mail address validator.

  1. ``` js
  2. const schema = {
  3.     email: { type: "email" }
  4. }
  5. const check = v.compile(schema);

  6. check({ email: "john.doe@gmail.com" }); // Valid
  7. check({ email: "james.123.45@mail.co.uk" }); // Valid
  8. check({ email: "abc@gmail" }); // Fail
  9. ```

Properties

Property | Default  | Description
empty  | false   | If true, the validator accepts an empty array "".
mode   | quick  | Checker method. Can be quick or precise.
normalize   | false  | Normalize the e-mail address (trim & lower-case). _It's a sanitizer, it will change the value in the original object._
min    | null   | Minimum value length.
max    | null   | Maximum value length.

enum

This is an enum validator.

  1. ``` js
  2. const schema = {
  3.     sex: { type: "enum", values: ["male", "female"] }
  4. }
  5. const check = v.compile(schema);

  6. check({ sex: "male" }); // Valid
  7. check({ sex: "female" }); // Valid
  8. check({ sex: "other" }); // Fail
  9. ```

Properties

Property | Default  | Description
values | null   | The valid values.

equal

This is an equal value validator. It checks a value with a static value or with another property.

Example with static value:
  1. ``` js
  2. const schema = {
  3.     agreeTerms: { type: "equal", value: true, strict: true } // strict means `===`
  4. }
  5. const check = v.compile(schema);

  6. check({ agreeTerms: true }); // Valid
  7. check({ agreeTerms: false }); // Fail
  8. ```

Example with other field:
  1. ``` js
  2. const schema = {
  3.     password: { type: "string", min: 6 },
  4.     confirmPassword: { type: "equal", field: "password" }
  5. }
  6. const check = v.compile(schema);

  7. check({ password: "123456", confirmPassword: "123456" }); // Valid
  8. check({ password: "123456", confirmPassword: "pass1234" }); // Fail
  9. ```

Properties

Property | Default  | Description
value  | undefined| The expected value. It can be any primitive types.
strict  | false| if true, it uses strict equal === for checking.

forbidden

This validator returns an error if the property exists in the object.

  1. ``` js
  2. const schema = {
  3.     password: { type: "forbidden" }
  4. }
  5. const check = v.compile(schema);

  6. check({ user: "John" }); // Valid
  7. check({ user: "John", password: "pass1234" }); // Fail
  8. ```

Properties

Property | Default  | Description
remove | false   | If true, the value will be removed in the original object. _It's a sanitizer, it will change the value in the original object._

Example for remove:
  1. ``` js
  2. const schema = {
  3.     user: { type: "string" },
  4.     token: { type: "forbidden", remove: true }
  5. };
  6. const check = v.compile(schema);

  7. const obj = {
  8.     user: "John",
  9.     token: "123456"
  10. }

  11. check(obj); // Valid
  12. console.log(obj);
  13. /*
  14. {
  15.     user: "John",
  16.     token: undefined
  17. }
  18. */
  19. ```

function

This a Function type validator.

  1. ``` js
  2. const schema = {
  3.     show: { type: "function" }
  4. }
  5. const check = v.compile(schema);

  6. check({ show: function() {} }); // Valid
  7. check({ show: Date.now }); // Valid
  8. check({ show: "function" }); // Fail
  9. ```

luhn

This is an Luhn validator.
Credit Card numbers, IMEI numbers, National Provider Identifier numbers and others

  1. ``` js
  2. const schema = {
  3.     cc: { type: "luhn" }
  4. }
  5. const check = v.compile(schema);

  6. check({ cc: "452373989901198" }); // Valid
  7. check({ cc: 452373989901198 }); // Valid
  8. check({ cc: "4523-739-8990-1198" }); // Valid
  9. check({ cc: "452373989901199" }); // Fail
  10. ```

mac

This is an MAC addresses validator.

  1. ``` js
  2. const schema = {
  3.     mac: { type: "mac" }
  4. }
  5. const check = v.compile(schema);

  6. check({ mac: "01:C8:95:4B:65:FE" }); // Valid
  7. check({ mac: "01:c8:95:4b:65:fe"); // Valid
  8. check({ mac: "01C8.954B.65FE" }); // Valid
  9. check({ mac: "01c8.954b.65fe"); // Valid
  10. check({ mac: "01-C8-95-4B-65-FE" }); // Valid
  11. check({ mac: "01-c8-95-4b-65-fe" }); // Valid
  12. check({ mac: "01C8954B65FE" }); // Fail
  13. ```

multi

This is a multiple definitions validator.

  1. ``` js
  2. const schema = {
  3.     status: { type: "multi", rules: [
  4.         { type: "boolean" },
  5.         { type: "number" }
  6.     ], default: true }
  7. }
  8. const check = v.compile(schema);

  9. check({ status: true }); // Valid
  10. check({ status: false }); // Valid
  11. check({ status: 1 }); // Valid
  12. check({ status: 0 }); // Valid
  13. check({ status: "yes" }); // Fail
  14. ```

Shorthand multiple definitions:
  1. ``` js
  2. const schema = {
  3.     status: [
  4.         "boolean",
  5.         "number"
  6.     ]
  7. }
  8. const check = v.compile(schema);

  9. check({ status: true }); // Valid
  10. check({ status: false }); // Valid
  11. check({ status: 1 }); // Valid
  12. check({ status: 0 }); // Valid
  13. check({ status: "yes" }); // Fail
  14. ```

number

This is a Number validator.

  1. ``` js
  2. const schema = {
  3.     age: { type: "number" }
  4. }
  5. const check = v.compile(schema);

  6. check({ age: 123 }); // Valid
  7. check({ age: 5.65 }); // Valid
  8. check({ age: "100" }); // Fail
  9. ```

Properties

Property | Default  | Description
min    | null   | Minimum value.
max    | null   | Maximum value.
equal  | null   | Fixed value.
notEqual | null | Can't be equal to this value.
integer | false | The value must be a non-decimal value.
positive | false| The value must be greater than zero.
negative | false| The value must be less than zero.
convert  | false| if true and the type is not Number, it's converted with Number(). _It's a sanitizer, it will change the value in the original object._

object

This is a nested object validator.

  1. ``` js
  2. const schema = {
  3.     address: { type: "object", strict: true, props: {
  4.         country: { type: "string" },
  5.         city: "string", // short-hand
  6.         zip: "number" // short-hand
  7.     } }
  8. }
  9. const check = v.compile(schema);

  10. check({
  11.     address: {
  12.         country: "Italy",
  13.         city: "Rome",
  14.         zip: 12345
  15.     }
  16. }); // Valid

  17. check({
  18.     address: {
  19.         country: "Italy",
  20.         city: "Rome"
  21.     }
  22. }); // Fail ("The 'address.zip' field is required!")

  23. check({
  24.     address: {
  25.         country: "Italy",
  26.         city: "Rome",
  27.         zip: 12345,
  28.         state: "IT"
  29.     }
  30. }); // Fail ("The 'address.state' is an additional field!")
  31. ```

Properties

Property | Default  | Description
strict  | false| If true any properties which are not defined on the schema will throw an error. If remove all additional properties will be removed from the original object. _It's a sanitizer, it will change the original object._
minProps | null | If set to a number N, will throw an error if the object has fewer than N properties.
maxProps | null | If set to a number N, will throw an error if the object has more than N properties.

  1. ``` js
  2. schema = {
  3.     address: { type: "object", strict: "remove", props: {
  4.         country: { type: "string" },
  5.         city: "string", // short-hand
  6.         zip: "number" // short-hand
  7.     } }
  8. }

  9. let obj = {
  10.     address: {
  11.         country: "Italy",
  12.         city: "Rome",
  13.         zip: 12345,
  14.         state: "IT"
  15.     }
  16. };
  17. const check = v.compile(schema);

  18. check(obj); // Valid
  19. console.log(obj);
  20. /*
  21. {
  22.     address: {
  23.         country: "Italy",
  24.         city: "Rome",
  25.         zip: 12345
  26.     }  
  27. }
  28. */
  29. ```
  1. ``` js
  2. schema = {
  3.   address: {
  4.     type: "object",
  5.     minProps: 2,
  6.     props: {
  7.       country: { type: "string" },
  8.       city: { type: "string", optional: true },
  9.       zip: { type: "number", optional: true }
  10.     }
  11.   }
  12. }
  13. const check = v.compile(schema);

  14. obj = {
  15.     address: {
  16.         country: "Italy",
  17.         city: "Rome",
  18.         zip: 12345,
  19.         state: "IT"
  20.     }
  21. }

  22. check(obj); // Valid

  23. obj = {
  24.     address: {
  25.         country: "Italy",
  26.     }
  27. }

  28. check(obj); // Fail
  29. // [
  30. //   {
  31. //     type: 'objectMinProps',
  32. //     message: "The object 'address' must contain at least 2 properties.",
  33. //     field: 'address',
  34. //     expected: 2,
  35. //     actual: 1
  36. //   }
  37. // ]
  38. ```

record

This validator allows to check an object with arbitrary keys.

  1. ``` js
  2. const schema = {
  3.     surnameGroups: {
  4.         type: 'record',
  5.         key: { type: 'string', alpha: true },
  6.         value: { type: 'array', items: 'string' }
  7.     }
  8. };
  9. const check = v.compile(schema);

  10. check({ surnameGroups: { Doe: ['Jane', 'John'], Williams: ['Bill'] } }); // Valid
  11. check({ surnameGroups: { Doe1: ['Jane', 'John'] } }); // Fail
  12. check({ surnameGroups: { Doe: [1, 'Jane'] } }); // Fail
  13. ```

Properties

Property | Default  | Description
key    | string | Key validation rule (It is reasonable to use only the string rule).
value  | any    | Value validation rule.

string

This is a String validator.

  1. ``` js
  2. const schema = {
  3.     name: { type: "string" }
  4. }
  5. const check = v.compile(schema);

  6. check({ name: "John" }); // Valid
  7. check({ name: "" }); // Valid
  8. check({ name: 123 }); // Fail
  9. ```

Properties

Property | Default  | Description
empty  | true   | If true, the validator accepts an empty string "".
min    | null   | Minimum value length.
max    | null   | Maximum value length.
length | null   | Fixed value length.
pattern | null   | Regex pattern.
contains | null   | The value must contain this text.
enum  | null   | The value must be an element of the enum array.
alpha   | null   | The value must be an alphabetic string.
numeric   | null   | The value must be a numeric string.
alphanum   | null   | The value must be an alphanumeric string.
alphadash   | null   | The value must be an alphabetic string that contains dashes.
hex   | null   | The value must be a hex string.
singleLine   | null   | The value must be a single line string.
base64   | null   | The value must be a base64 string.
trim   | null   | If true, the value will be trimmed. _It's a sanitizer, it will change the value in the original object._
trimLeft   | null   | If true, the value will be left trimmed. _It's a sanitizer, it will change the value in the original object._
trimRight   | null   | If true, the value will be right trimmed. _It's a sanitizer, it will change the value in the original object._
padStart   | null   | If it's a number, the value will be left padded. _It's a sanitizer, it will change the value in the original object._
padEnd   | null   | If it's a number, the value will be right padded. _It's a sanitizer, it will change the value in the original object._
padChar   | " "   | The padding character for the padStart and padEnd.
lowercase   | null   | If true, the value will be lower-cased. _It's a sanitizer, it will change the value in the original object._
uppercase   | null   | If true, the value will be upper-cased. _It's a sanitizer, it will change the value in the original object._
localeLowercase   | null   | If true, the value will be locale lower-cased. _It's a sanitizer, it will change the value in the original object._
localeUppercase   | null   | If true, the value will be locale upper-cased. _It's a sanitizer, it will change the value in the original object._
convert  | false| if true and the type is not a String, it's converted with String(). _It's a sanitizer, it will change the value in the original object._

Sanitization example
  1. ``` js
  2. const schema = {
  3.     username: { type: "string", min: 3, trim: true, lowercase: true}
  4. }
  5. const check = v.compile(schema);

  6. const obj = {
  7.     username: "   Icebob  "
  8. };

  9. check(obj); // Valid
  10. console.log(obj);
  11. /*
  12. {
  13.     username: "icebob"
  14. }
  15. */
  16. ```

tuple

This validator checks if a value is an Array with the elements order as described by the schema.

Simple example:
  1. ``` js
  2. const schema = { list: "tuple" };
  3. const check = v.compile(schema);

  4. check({ list: [] }); // Valid
  5. check({ list: [1, 2] }); // Valid
  6. check({ list: ["RON", 100, true] }); // Valid
  7. check({ list: 94 }); // Fail (not an array)
  8. ```

Example with items:
  1. ``` js
  2. const schema = {
  3.     grade: { type: "tuple", items: ["string", "number"] }
  4. }
  5. const check = v.compile(schema);

  6. check({ grade: ["David", 85] }); // Valid
  7. check({ grade: [85, "David"] }); // Fail (wrong position)
  8. check({ grade: ["Cami"] }); // Fail (require 2 elements)
  9. ```

Example with a more detailed schema:
  1. ``` js
  2. const schema = {
  3.     location: { type: "tuple", items: [
  4.         "string",
  5.         { type: "tuple", empty: false, items: [
  6.             { type: "number", min: 35, max: 45 },
  7.             { type: "number", min: -75, max: -65 }
  8.         ] }
  9.     ] }
  10. }
  11. const check = v.compile(schema);

  12. check({ location: ['New York', [40.7127281, -74.0060152]] }); // Valid
  13. check({ location: ['New York', [50.0000000, -74.0060152]] }); // Fail
  14. check({ location: ['New York', []] }); // Fail (empty array)
  15. ```

Properties

Property | Default  | Description
empty  | true   | If true, the validator accepts an empty array [].
items  | undefined | Exact schema of the value items

url

This is an URL validator.

  1. ``` js
  2. const schema = {
  3.     url: { type: "url" }
  4. }
  5. const check = v.compile(schema);

  6. check({ url: "http://google.com" }); // Valid
  7. check({ url: "https://github.com/icebob" }); // Valid
  8. check({ url: "www.facebook.com" }); // Fail
  9. ```

Properties

Property | Default  | Description
empty  | false   | If true, the validator accepts an empty string "".

uuid

This is an UUID validator.

  1. ``` js
  2. const schema = {
  3.     uuid: { type: "uuid" }
  4. }
  5. const check = v.compile(schema);

  6. check({ uuid: "00000000-0000-0000-0000-000000000000" }); // Valid Nil UUID
  7. check({ uuid: "10ba038e-48da-487b-96e8-8d3b99b6d18a" }); // Valid UUIDv4
  8. check({ uuid: "9a7b330a-a736-51e5-af7f-feaf819cdc9f" }); // Valid UUIDv5
  9. check({ uuid: "10ba038e-48da-487b-96e8-8d3b99b6d18a", version: 5 }); // Fail
  10. ```

Properties

Property | Default  | Description
version  | null   | UUID version in range 0-6. The null disables version checking.

objectID

You can validate BSON/MongoDB ObjectID's
  1. ``` js
  2. const  { ObjectID } = require("mongodb") // or anywhere else

  3. const schema = {
  4.     id: {
  5.         type: "objectID",
  6.         ObjectID // passing the ObjectID class
  7.     }  
  8. }
  9. const check = v.compile(schema);

  10. check({ id: "5f082780b00cc7401fb8e8fc" }) // ok
  11. check({ id: new ObjectID() }) // ok
  12. check({ id: "5f082780b00cc7401fb8e8" }) // Error
  13. ```

Pro tip:  By using defaults props for objectID rule, No longer needed to pass ObjectID class in validation schema:

  1. ``` js
  2. const  { ObjectID } = require("mongodb") // or anywhere else

  3. const v = new Validator({
  4.     defaults: {
  5.         objectID: {
  6.             ObjectID
  7.         }
  8.     }
  9. })

  10. const schema = {
  11.     id: "objectID"
  12. }
  13. ```

Properties

Property | Default  | Description
convert  | false   | If true, the validator converts ObjectID HexString representation to ObjectID instance, if hexString the validator converts to HexString

Custom validator

You can also create your custom validator.

  1. ``` js
  2. const v = new Validator({
  3.     messages: {
  4.         // Register our new error message text
  5.         evenNumber: "The '{field}' field must be an even number! Actual: {actual}"
  6.     }
  7. });

  8. // Register a custom 'even' validator
  9. v.add("even", function({ schema, messages }, path, context) {
  10.     return {
  11.         source: `
  12.             if (value % 2 != 0)
  13.                 ${this.makeError({ type: "evenNumber",  actual: "value", messages })}

  14.             return value;
  15.         `
  16.     };
  17. });

  18. const schema = {
  19.     name: { type: "string", min: 3, max: 255 },
  20.     age: { type: "even" }
  21. };
  22. const check = v.compile(schema);

  23. console.log(check({ name: "John", age: 20 }, schema));
  24. // Returns: true

  25. console.log(check({ name: "John", age: 19 }, schema));
  26. /* Returns an array with errors:
  27.     [{
  28.         type: 'evenNumber',
  29.         expected: null,
  30.         actual: 19,
  31.         field: 'age',
  32.         message: 'The \'age\' field must be an even number! Actual: 19'
  33.     }]
  34. */
  35. ```

Or you can use the custom type with an inline checker function:
  1. ``` js
  2. const v = new Validator({
  3.     useNewCustomCheckerFunction: true, // using new version
  4.     messages: {
  5.         // Register our new error message text
  6.         weightMin: "The weight must be greater than {expected}! Actual: {actual}"
  7.     }
  8. });

  9. const schema = {
  10.     name: { type: "string", min: 3, max: 255 },
  11.     weight: {
  12.         type: "custom",
  13.         minWeight: 10,
  14.         check(value, errors, schema) {
  15.             if (value < minWeight) errors.push({ type: "weightMin", expected: schema.minWeight, actual: value });
  16.             if (value > 100) value = 100
  17.             return value
  18.         }
  19.     }
  20. };
  21. const check = v.compile(schema);

  22. console.log(check({ name: "John", weight: 50 }, schema));
  23. // Returns: true

  24. console.log(check({ name: "John", weight: 8 }, schema));
  25. /* Returns an array with errors:
  26.     [{
  27.         type: 'weightMin',
  28.         expected: 10,
  29.         actual: 8,
  30.         field: 'weight',
  31.         message: 'The weight must be greater than 10! Actual: 8'
  32.     }]
  33. */
  34. const o = { name: "John", weight: 110 }
  35. console.log(check(o, schema));
  36. /* Returns: true
  37.    o.weight is 100
  38. */
  39. ```
>Please note: the custom function must return the value. It means you can also sanitize it.

Custom validation for built-in rules

You can define a custom function in the schema for built-in rules. With it you can extend any built-in rules.

  1. ``` js
  2. const v = new Validator({
  3.     useNewCustomCheckerFunction: true, // using new version
  4.     messages: {
  5.         // Register our new error message text
  6.         phoneNumber: "The phone number must be started with '+'!"
  7.     }
  8. });

  9. const schema = {
  10.     name: { type: "string", min: 3, max: 255 },
  11.     phone: { type: "string", length: 15, custom: (v, errors) => {
  12.             if (!v.startsWith("+")) errors.push({ type: "phoneNumber" })
  13.             return v.replace(/[^\d+]/g, ""); // Sanitize: remove all special chars except numbers
  14.         }
  15.     }
  16. };
  17. const check = v.compile(schema);

  18. console.log(check({ name: "John", phone: "+36-70-123-4567" }));
  19. // Returns: true

  20. console.log(check({ name: "John", phone: "36-70-123-4567" }));
  21. /* Returns an array with errors:
  22.     [{
  23.         message: "The phone number must be started with '+'!",
  24.         field: 'phone',
  25.         type: 'phoneNumber'
  26.     }]
  27. */
  28. ```

>Please note: the custom function must return the value. It means you can also sanitize it.

Asynchronous custom validations

You can also use async custom validators. This can be useful if you need to check something in a database or in a remote location.
In this case you should use async/await keywords, or return a Promise in the custom validator functions.

>This implementation uses async/await keywords. So this feature works only on environments which supports async/await:
>

- Chrome > 55

- Firefox > 52

- Edge > 15

- NodeJS > 8.x (or 7.6 with harmony)

- Deno (all versions)


To enable async mode, you should set $$async: true in the root of your schema.

Example with custom checker function
  1. ``` js
  2. const v = new Validator({
  3.     useNewCustomCheckerFunction: true, // using new version
  4.     messages: {
  5.         // Register our new error message text
  6.         unique: "The username is already exist"
  7.     }
  8. });

  9. const schema = {
  10.     $$async: true,
  11.     name: { type: "string" },
  12.     username: {
  13.         type: "string",
  14.         min: 2,
  15.         custom: async (v, errors) => {
  16.             // E.g. checking in the DB that the value is unique.
  17.             const res = await DB.checkUsername(v);
  18.             if (!res)
  19.                 errors.push({ type: "unique", actual: value });

  20.             return v;
  21.         }
  22.     }
  23.     // ...
  24. };

  25. const check = v.compile(schema);

  26. const res = await check(user);
  27. console.log("Result:", res);
  28. ```

The compiled check function contains an async property, so  you can check if it returns a Promise or not.
  1. ``` js
  2. const check = v.compile(schema);
  3. console.log("Is async?", check.async);
  4. ```

Meta information for custom validators

You can pass any extra meta information for the custom validators which is available via context.meta.

  1. ``` js
  2. const schema = {
  3.     name: { type: "string", custom: (value, errors, schema, name, parent, context) => {
  4.         // Access to the meta
  5.         return context.meta.a;
  6.     } },
  7. };
  8. const check = v.compile(schema);

  9. const res = check(obj, {
  10.     // Passes meta information
  11.     meta: { a: "from-meta" }
  12. });
  13. ```

Custom error messages (l10n)

You can set your custom messages in the validator constructor.

  1. ``` js
  2. const Validator = require("fastest-validator");
  3. const v = new Validator({
  4.     messages: {
  5.         stringMin: "A(z) '{field}' mező túl rövid. Minimum: {expected}, Jelenleg: {actual}",
  6.         stringMax: "A(z) '{field}' mező túl hosszú. Minimum: {expected}, Jelenleg: {actual}"
  7.     }
  8. });

  9. const schema = {
  10.     name: { type: "string", min: 6 }
  11. }
  12. const check = v.compile(schema);

  13. check({ name: "John" });
  14. /* Returns:
  15. [
  16.     {
  17.         type: 'stringMin',
  18.         expected: 6,
  19.         actual: 4,
  20.         field: 'name',
  21.         message: 'A(z) \'name\' mező túl rövid. Minimum: 6, Jelenleg: 4'
  22.     }
  23. ]
  24. */
  25. ```

Personalised Messages

Sometimes the standard messages are too generic. You can customize messages per validation type per field:

  1. ``` js
  2. const Validator = require("fastest-validator");
  3. const v = new Validator();
  4. const schema = {
  5.     firstname: {
  6.         type: "string",
  7.         min: 6,
  8.         messages: {
  9.             string: "Please check your firstname",
  10.             stringMin: "Your firstname is too short"
  11.         }
  12.     },
  13.     lastname: {
  14.         type: "string",
  15.         min: 6,
  16.         messages: {
  17.             string: "Please check your lastname",
  18.             stringMin: "Your lastname is too short"
  19.         }
  20.     }
  21. }
  22. const check = v.compile(schema);

  23. check({ firstname: "John", lastname: 23 });
  24. /* Returns:
  25. [
  26.     {
  27.         type: 'stringMin',
  28.         expected: 6,
  29.         actual: 4,
  30.         field: 'firstname',
  31.         message: 'Your firstname is too short'
  32.     },
  33.     {
  34.         type: 'string',
  35.         expected: undefined,
  36.         actual: undefined,
  37.         field: 'lastname',
  38.         message: 'Please check your lastname'
  39.     }
  40. ]
  41. */
  42. ```

Plugins

You can apply plugins:
  1. ``` js
  2. // Plugin Side
  3. function myPlugin(validator){
  4.     // you can modify validator here
  5.     // e.g.: validator.add(...)
  6. }

  7. // Validator Side
  8. const v = new Validator();
  9. v.plugin(myPlugin)

  10. ```

Message types

Name                | Default text
required | The '{field}' field is required.
string | The '{field}' field must be a string.
stringEmpty | The '{field}' field must not be empty.
stringMin | The '{field}' field length must be greater than or equal to {expected} characters long.
stringMax | The '{field}' field length must be less than or equal to {expected} characters long.
stringLength | The '{field}' field length must be {expected} characters long.
stringPattern | The '{field}' field fails to match the required pattern.
stringContains | The '{field}' field must contain the '{expected}' text.
stringEnum | The '{field}' field does not match any of the allowed values.
stringNumeric | The '{field}' field must be a numeric string.
stringAlpha | The '{field}' field must be an alphabetic string.
stringAlphanum | The '{field}' field must be an alphanumeric string.
stringAlphadash | The '{field}' field must be an alphadash string.
stringHex | The '{field}' field must be a hex string.
stringSingleLine | The '{field}' field must be a single line string.
stringBase64 | The '{field}' field must be a base64 string.
number | The '{field}' field must be a number.
numberMin | The '{field}' field must be greater than or equal to {expected}.
numberMax | The '{field}' field must be less than or equal to {expected}.
numberEqual | The '{field}' field must be equal to {expected}.
numberNotEqual | The '{field}' field can't be equal to {expected}.
numberInteger | The '{field}' field must be an integer.
numberPositive | The '{field}' field must be a positive number.
numberNegative | The '{field}' field must be a negative number.
array | The '{field}' field must be an array.
arrayEmpty | The '{field}' field must not be an empty array.
arrayMin | The '{field}' field must contain at least {expected} items.
arrayMax | The '{field}' field must contain less than or equal to {expected} items.
arrayLength | The '{field}' field must contain {expected} items.
arrayContains | The '{field}' field must contain the '{expected}' item.
arrayUnique | The '{actual}' value in '{field}' field does not unique the '{expected}' values.
arrayEnum | The '{actual}' value in '{field}' field does not match any of the '{expected}' values.
tuple | The '{field}' field must be an array.
tupleEmpty | The '{field}' field must not be an empty array.
tupleLength | The '{field}' field must contain {expected} items.
boolean | The '{field}' field must be a boolean.
function | The '{field}' field must be a function.
date | The '{field}' field must be a Date.
dateMin | The '{field}' field must be greater than or equal to {expected}.
dateMax | The '{field}' field must be less than or equal to {expected}.
forbidden | The '{field}' field is forbidden.
‍‍email | The '{field}' field must be a valid e-mail.
emailEmpty | The '{field}' field must not be empty.
emailMin | The '{field}' field length must be greater than or equal to {expected} characters long.
emailMax | The '{field}' field length must be less than or equal to {expected} characters long.
url | The '{field}' field must be a valid URL.
enumValue | The '{field}' field value '{expected}' does not match any of the allowed values.
equalValue | The '{field}' field value must be equal to '{expected}'.
equalField | The '{field}' field value must be equal to '{expected}' field value.
object | The '{field}' must be an Object.
objectStrict | The object '{field}' contains forbidden keys: '{actual}'.
objectMinProps | "The object '{field}' must contain at least {expected} properties.
objectMaxProps | "The object '{field}' must contain {expected} properties at most.
uuid | The '{field}' field must be a valid UUID.
uuidVersion | The '{field}' field must be a valid UUID version provided.
mac | The '{field}' field must be a valid MAC address.
luhn | The '{field}' field must be a valid checksum luhn.

Message fields

Name        | Description
field     | The field name
expected  | The expected value
actual    | The actual value

Development

  1. ```
  2. npm run dev
  3. ```

Test

  1. ```
  2. npm test
  3. ```

Coverage report

  1. ```
  2. -----------------|----------|----------|----------|----------|-------------------|
  3. File             |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
  4. -----------------|----------|----------|----------|----------|-------------------|
  5. All files        |      100 |    97.73 |      100 |      100 |                   |
  6. lib             |      100 |      100 |      100 |      100 |                   |
  7.   messages.js    |      100 |      100 |      100 |      100 |                   |
  8.   validator.js   |      100 |      100 |      100 |      100 |                   |
  9. lib/helpers     |      100 |      100 |      100 |      100 |                   |
  10.   deep-extend.js |      100 |      100 |      100 |      100 |                   |
  11.   flatten.js     |      100 |      100 |      100 |      100 |                   |
  12. lib/rules       |      100 |    96.43 |      100 |      100 |                   |
  13.   any.js         |      100 |      100 |      100 |      100 |                   |
  14.   array.js       |      100 |      100 |      100 |      100 |                   |
  15.   boolean.js     |      100 |      100 |      100 |      100 |                   |
  16.   custom.js      |      100 |       50 |      100 |      100 |                 6 |
  17.   date.js        |      100 |      100 |      100 |      100 |                   |
  18.   email.js       |      100 |      100 |      100 |      100 |                   |
  19.   enum.js        |      100 |       50 |      100 |      100 |                 6 |
  20.   equal.js       |      100 |      100 |      100 |      100 |                   |
  21.   forbidden.js   |      100 |      100 |      100 |      100 |                   |
  22.   function.js    |      100 |      100 |      100 |      100 |                   |
  23.   luhn.js        |      100 |      100 |      100 |      100 |                   |
  24.   mac.js         |      100 |      100 |      100 |      100 |                   |
  25.   multi.js       |      100 |      100 |      100 |      100 |                   |
  26.   number.js      |      100 |      100 |      100 |      100 |                   |
  27.   object.js      |      100 |      100 |      100 |      100 |                   |
  28.   string.js      |      100 |    95.83 |      100 |      100 |             55,63 |
  29.   tuple.js       |      100 |      100 |      100 |      100 |                   |
  30.   url.js         |      100 |      100 |      100 |      100 |                   |
  31.   uuid.js        |      100 |      100 |      100 |      100 |                   |
  32. -----------------|----------|----------|----------|----------|-------------------|
  33. ```

Contribution

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

License

fastest-validator is available under the MIT license.

Contact


Copyright (C) 2019 Icebob
@icebob @icebob