Jet-Validator
A super quick, easy to setup validation middleware function for ExpresssJS routes. Written in typescript ann fully typesafe :)
Quick start
-
Call the
jetValidator()
function to return thevalidate()
middleware function. If the validation fails, validate will return a400
error with an error message. If you want to change the error status code, you can passjetValidator()
an optional parameter. -
Arguments to
validate()
must be a string or an array. If they're a string,validate()
will make sure they are string onreq.body
. -
Note:
json()
andurlencoded()
middleware must be added to express.
import express, { Request, Response } from 'express';
import jetValidator from 'jet-validator';
const app = express(),
validate = jetValidator();
app.post(
'/api/v1/login/local',
validate('email', 'password'), // Will check that email and password are strings on req.body
(req: Request, res: Response) => {
const { email, password } = req.body;
...etc,
},
);
Full guide
-
As mentioned in the Quick Start,
validate()
accepts a string or an array. -
If a string,
validate()
makes sure the arguments is of typestring
onreq.body
. -
If the argument is an array the format is:
[
'paramName',
'(optional) type or validator function (default is string)',
'(optional) property on "express.Request" to extract the value from (default is .body')
]
-
For arrays,
validate()
makes sure the parameter is of the specified type or that the parameter satifies the validator function. The validator function must returntrue
orfalse
. -
Sample array1:
['id', 'number', 'body']
. This will make sureid
is of typenumber
onreq.body
. -
Sample array2:
['email', isEmail]
. This will make surereq.body.email
satifies theisEmail
function. -
Note for numbers on
req.query
andreq.params
: number-strings which pass!isNaN()
are still valid. But onreq.body
a number should betypeof toCheck === "number"
. -
For booleans on
req.query
andreq.params
: boolean strings should be"true"
or"false"
, but onreq.body
a boolean shouldtypeof toCheck === "boolean"
.
More examples
-
Example 1:
validate('email', ['user', 'object'], ['id', 'number', 'params'])
will check thatemail
is astring
inreq.body
, thatuser
is of typeobject
inreq.body
, and thatid
is anumber
inreq.params
. -
Example 2:
validate('password')
will check thatpassword
is astring
onreq.body
. -
Example 3:
validate(['isAdmin', 'boolean'])
will check thatisAdmin
is aboolean
onreq.body
. -
Example 4:
validate(['user', isInstanceOfUser])
will check thatreq.body.user
satifies theisInstanceOfUser()
function. -
Example 5:
validate(['email'])
will check thatemail
is a string inreq.body
. -
Example 6:
validate(['id', 'number', 'params'])
will check thatid
is a number-string inreq.params
.