:zap: The fastest JS validator library for NodeJS
:zap: The fastest JS validator library for NodeJS
:zap: The fastest JS validator library for NodeJS | Browser | Deno.
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
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.
You can install it via NPM.
$ npm i fastest-validator --save
or
$ yarn add fastest-validator
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.
…
If you want to halt immediately after the first error:
const v = new Validator({ haltOnFirstError: true });
<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
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
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
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
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
null as a valueIn specific case, you may want to consider null as a valid input even for a required field.
It's useful in cases you want a field to be:
required and null without specifying nullable: true in its definition.required and not null by specifying nullable: false in its definition.optional but specifically not null.To be able to achieve this you'll have to set the considerNullAsAValue validator option to true.
const v = new Validator({considerNullAsAValue: true});
const schema = {foo: {type: "number"}, bar: {type: "number", optional: true, nullable: false}, baz: {type: "number", nullable: false}};
const check = v.compile(schema);
const object1 = {foo: null, baz: 1};
check(object1); // valid (foo is required and can be null)
const object2 = {foo: 3, bar: null, baz: 1};
check(object2); // not valid (bar is optional but can't be null)
const object3 = {foo: 3, baz: null};
check(object3); // not valid (baz is required but can't be null)
With this option set all fields will be considered nullable by default.
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
To remove the additional fields in the object, set $$strict: "remove".
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
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.
The library contains several sanitizers. Please note, the sanitizers change the original checked object.
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)
}
*/
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
}
const schema = {
foo: "string[]" // means array of string
}
const check = v.compile(schema);
check({ foo: ["bar"] }) // true
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"
}
};
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",
}
You can set default rule options.
const v = new FastestValidator({
defaults: {
object: {
strict: "remove"
}
}
});
You can use label names in error messages instead of property names.
const schema = {
email: { type: "email", label: "Email Address" },
};
const check = v.compile(schema);
console.log(check({ email: "notAnEmail" }));
/* Returns
[
{
type: 'email',
message: "The 'Email Address' field must be a valid e-mail.",
field: 'email',
actual: 'notAnEmail',
label: 'Email Address'
}
]
*/
anyThis 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
arrayThis 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
Example for convert:
const schema = {
roles: { type: "array", items: 'string', convert: true }
}
const check = v.compile(schema);
check({ roles: ["user"] }); // Valid
check({ roles: "user" }); // Valid
// After both validation: roles = ["user"]
No open issues yet, or sync has not completed.