Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
F

fastest-validator

> 编程语言
Open source

:zap: The fastest JS validator library for NodeJS

1.5K stars0 likes0 views
WebsiteGitHub

About

:zap: The fastest JS validator library for NodeJS

fastest-validator

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

Key features

  • blazing fast! Really!
  • 24 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.

…

Try it on Repl.it

Halting

If you want to halt immediately after the first error:

const v = new Validator({ haltOnFirstError: true });

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

Considering null as a value

In 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.

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"
        }
    }
});

Label Option

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'
  }
]
*/

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

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"]

Pro

Issues· 45 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScriptschemaschema-validationvalidatevalidator

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言