Skip to content

Middleware

A Validation object created with the Validation.profile() method can be used as a middleware function on the server side.

Syntax

Validation()(req, res, next)
// as Express middleware
app.post(url, Validation())

Parameters

Please refer to Express documentation.

Return value

None (undefined).

Exceptions

If invoked without having created a validation profile, throws the corresponding error. Also see “Exceptions” of the Validation().validate() method.

Description

When invoked on the server side, runs a data mapper function and the Validation().validate() method. Assigns a validation result to the incoming request object which can be accessed in the next executed middleware. Only validations created with the Validation.profile() method can be used as middleware functions.

Using a Validation object as a middleware function is intended to reduce boilerplate code.

Examples

import express from 'express';
import bodyParser from 'body-parser';
// validations created with the `Validation.profile()` method
import { signinV, signupV } from 'your-validations-file-name.js';
const app = express();
const urlencodeParser = bodyParser.urlencoded({extended: false});
function signinRequestHandler(req, res) {
const { validationResult } = req;
if (validationResult.isValid) {
// check credentials
// ...
}
else {
// respond with the validation error
// ...
}
}
function signupRequestHandler(req, res) {
const { validationResult } = req;
if (validationResult.isValid) {
// create an account
// ...
}
else {
// respond with the validation error
// ...
}
}
// validations are added as middleware functions
app.post('/signin', urlencodeParser, signinV, signinRequestHandler);
app.post('/signup', urlencodeParser, signupV, signupRequestHandler);