jet-validator v1.1.1
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 a400error 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 typestringonreq.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 returntrueorfalse.Sample array1:
['id', 'number', 'body']. This will make sureidis of typenumberonreq.body.Sample array2:
['email', isEmail]. This will make surereq.body.emailsatifies theisEmailfunction.Note for numbers on
req.queryandreq.params: number-strings which pass!isNaN()are still valid. But onreq.bodya number should betypeof toCheck === "number".For booleans on
req.queryandreq.params: boolean strings should be"true"or"false", but onreq.bodya boolean shouldtypeof toCheck === "boolean".
More examples
Example 1:
validate('email', ['user', 'object'], ['id', 'number', 'params'])will check thatemailis astringinreq.body, thatuseris of typeobjectinreq.body, and thatidis anumberinreq.params.Example 2:
validate('password')will check thatpasswordis astringonreq.body.Example 3:
validate(['isAdmin', 'boolean'])will check thatisAdminis abooleanonreq.body.Example 4:
validate(['user', isInstanceOfUser])will check thatreq.body.usersatifies theisInstanceOfUser()function.Example 5:
validate(['email'])will check thatemailis a string inreq.body.Example 6:
validate(['id', 'number', 'params'])will check thatidis a number-string inreq.params.