-
For most of the framework, you can use
sanitizenode module:npm install sanitize --saveAnd then can use like:
var sanitizer = require('sanitize')(); var name = sanitizer.value(req.name, 'string'); var surname= sanitizer.value(req.surname, 'string');For more can go through sanitize documentation
-
If you are using
express, then you can validate and sanitize using express-validator and express-sanitize-input packages as follows:const express = require('express'); const { check } = require('express-validator'); const app = express(); app.use(express.json()) app.post('/form', [ check('name').isLength({ min: 3 }).trim().escape(), check('email').isEmail().normalizeEmail(), check('age').isNumeric().trim().escape() ], (req, res) => { const name = req.body.name const email = req.body.email const age = req.body.age })For more can go through express-validator and express-sanitize-input documentation.
-
If you are using
Hapi, then you can validate and sanitize using Joi, With the Joi, you can sanitize variable with additional optionsvalidate(value, schema, {escapeHtml: true}, [callback])For more can go through Joi documentation.
-
If you don’t want to use any third party module and want to sanitize using the built-in node. you can try following:
// For string variables str = typeof(str) === 'string' && str.trim().length > 0 ? str.trim() : ''; // for boolean values bool = typeof(bool) === 'boolean' && bool === true ? true : false; // for array values arr = typeof(arr) === 'object' && arr instanceof Array ? arr : []; // for number values num = typeof(num) === 'number' && num % 1 === 0 ? num : 0; // for objects obj = typeof(obj) === 'object' && !(obj instanceof Array) && obj !== null ? obj : {};