README
fastest-validator
: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)
√ validate 8,678,752 rps
Compared to other popular libraries:
50x faster than Joi.
Would you like to test it?
$ git clone https://github.com/icebob/fastest-validator.git
$ cd fastest-validator
$ npm install
$ npm run bench
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.
$ npm i fastest-validator --save
or
$ yarn add fastest-validator
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.
const Validator = require("fastest-validator");
const v = new Validator();
const schema = {
id: { type: "number", positive: true, integer: true },
name: { type: "string", min: 3, max: 255 },
status: "boolean" // short-hand def
};
const check = v.compile(schema);
console.log("First:", check({ id: 5, name: "John", status: true }));
// Returns: true
console.log("Second:", check({ id: 2, name: "Adam" }));
/* Returns an array with errors:
[
{
type: 'required',
field: 'status',
message: 'The \'status\' field is required!'
}
]
*/
Browser usage
<script src="https://unpkg.com/fastest-validator"></script>
const v = new FastestValidator();
const schema = {
id: { type: "number", positive: true, integer: true },
name: { type: "string", min: 3, max: 255 },
status: "boolean" // short-hand def
};
const check = v.compile(schema);
console.log(check({ id: 5, name: "John", status: true }));
// Returns: true
Deno usage
With esm.sh
, now Typescript is supported
import FastestValidator from "https://esm.sh/fastest-validator@1"
const v = new FastestValidator();
const check = v.compile({
name: "string",
age: "number",
});
console.log(check({ name: "Erf", age: 18 })); //true
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
.
const schema = {
name: { type: "string" }, // required
age: { type: "number", optional: true }
}
const check = v.compile(schema);
check({ name: "John", age: 42 }); // Valid
check({ name: "John" }); // Valid
check({ age: 42 }); // Fail because name is required
Nullable
If you want disallow undefined
value but allow null
value, use nullable
instead of optional
.
const schema = {
age: { type: "number", nullable: true }
}
const check = v.compile(schema);
check({ age: 42 }); // Valid
check({ age: null }); // Valid
check({ age: undefined }); // Fail because undefined is disallowed
check({}); // Fail because undefined is disallowed
Nullable and default values
null
is a valid input for nullable fields that has default value.
const schema = {
about: { type: "string", nullable: true, default: "Hi! I'm using javascript" }
}
const check = v.compile(schema)
const object1 = { about: undefined }
check(object1) // Valid
object1.about // is "Hi! I'm using javascript"
const object2 = { about: null }
check(object2) // valid
object2.about // is null
check({ about: "Custom" }) // Valid
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.
const schema = {
name: { type: "string" }, // required
$strict: true // no additional properties allowed
}
const check = v.compile(schema);
check({ name: "John" }); // Valid
check({ name: "John", age: 42 }); // Fail
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.
const schema = {
cache: [
{ type: "string" },
{ type: "boolean" }
]
}
const check = v.compile(schema);
check({ cache: true }); // Valid
check({ cache: "redis://" }); // Valid
check({ cache: 150 }); // Fail
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
const schema = {
$root: true,
type: "string",
min: 3,
max: 6
};
const check = v.compile(schema);
check("John"); // Valid
check("Al"); // Fail, too short.
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:
const schema = {
roles: { type: "array", items: "string", default: ["user"] },
status: { type: "boolean", default: true },
};
const check = v.compile(schema);
const obj = {}
check(obj); // Valid
console.log(obj);
/*
{
roles: ["user"],
status: true
}
*/
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:
const schema = {
createdAt: {
type: "date",
default: (schema, field, parent, context) => new Date()
}
};
const check = v.compile(schema);
const obj = {}
check(obj); // Valid
console.log(obj);
/*
{
createdAt: Date(2020-07-25T13:17:41.052Z)
}
*/
Shorthand definitions
You can use string-based shorthand validation definitions in the schema.
const schema = {
password: "string|min:6",
age: "number|optional|integer|positive|min:0|max:99", // additional properties
state: ["boolean", "number|min:0|max:1"] // multiple types
}
Array of X
const schema = {
foo: "string[]" // means array of string
}
const check = v.compile(schema);
check({ foo: ["bar"] }) // true
Nested objects
const schema = {
dot: {
$type: "object",
x: "number", // object props here
y: "number", // object props here
},
circle: {
$type: "object|optional", // using other shorthands
o: {
$type: "object",
x: "number",
y: "number",
},
r: "number"
}
};
Alias definition
You can define custom aliases.
v.alias('username', {
type: 'string',
min: 4,
max: 30
// ...
});
const schema = {
username: "username|max:100", // Using the 'username' alias
password: "string|min:6",
}
Default options
You can set default rule options.
const v = new FastestValidator({
defaults: {
object: {
strict: "remove"
}
}
});
Built-in validators
any
This does not do type validation. Accepts any types.
const schema = {
prop: { type: "any" }
}
const check = v.compile(schema)
check({ prop: true }); // Valid
check({ prop: 100 }); // Valid
check({ prop: "John" }); // Valid
array
This is an Array
validator.
Simple example with strings:
const schema = {
roles: { type: "array", items: "string" }
}
const check = v.compile(schema)
check({ roles: ["user"] }); // Valid
check({ roles: [] }); // Valid
check({ roles: "user" }); // Fail
Example with only positive numbers:
const schema = {
list: { type: "array", min: 2, items: {
type: "number", positive: true, integer: true
} }
}
const check = v.compile(schema)
check({ list: [2, 4] }); // Valid
check({ list: [1, 5, 8] }); // Valid
check({ list: [1] }); // Fail (min 2 elements)
check({ list: [1, -7] }); // Fail (negative number)
Example with an object list:
const schema = {
users: { type: "array", items: {
type: "object", props: {
id: { type: "number", positive: true },
name: { type: "string", empty: false },
status: "boolean"
}
} }
}
const check = v.compile(schema)
check({
users: [
{ id: 1, name: "John", status: true },
{ id: 2, name: "Jane", status: true },
{ id: 3, name: "Bill", status: false }
]
}); // Valid
Example for enum
:
const schema = {
roles: { type: "array", items: "string", enum: [ "user", "admin" ] }
}
const check = v.compile(schema)
check({ roles: ["user"] }); // Valid
check({ roles: ["user", "admin"] }); // Valid
check({ roles: ["guest"] }); // Fail
Example for unique
:
const schema = {
roles: { type: "array", unique: true }
}
const check = v.compile(schema);
check({ roles: ["user"] }); // Valid
check({ roles: [{role:"user"},{role:"admin"},{role:"user"}] }); // Valid
check({ roles: ["user", "admin", "user"] }); // Fail
check({ roles: [1, 2, 1] }); // Fail
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.
const schema = {
status: { type: "boolean" }
}
const check = v.compile(schema);
check({ status: true }); // Valid
check({ status: false }); // Valid
check({ status: 1 }); // Fail
check({ status: "true" }); // Fail
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
:
const schema = {
status: { type: "boolean", convert: true}
};
const check = v.compile(schema);
check({ status: "true" }); // Valid
class
This is a Class
validator to check the value is an instance of a Class.
const schema = {
rawData: { type: "class", instanceOf: Buffer }
}
const check = v.compile(schema);
check({ rawData: Buffer.from([1, 2, 3]) }); // Valid
check({ rawData: 100 }); // Fail
Properties
Property | Default | Description |
---|---|---|
instanceOf |
null |
Checked Class. |
currency
This is a Currency
validator to check if the value is a valid currency string.
const schema = {
money_amount: { type: "currency", currencySymbol: '