I validated my Node.js inputs so that they won't be empty, but I want to sanitize them too. Please help me how I can do this.
req.checkBody('name', 'Name is required!').notEmpty(); req.checkBody('surname', 'Surname is required!').notEmpty(); req.checkBody('username', 'Username is required!').notEmpty(); req.checkBody('password', 'Password is required!').notEmpty(); req.checkBody('password2', 'Passwords do not match!').equals(req.body.password); var errors = req.validationErrors(); if (errors) { res.render('user/register', { errors: errors, user: null, title: 'Register' }); } else { var userData = { name : req.body.name, surname : req.body.surname, username : req.body.username, password : req.body.password, avatar : 'No_person.jpg' }; userController.addUser(req,res,userData); }
Sanitizing and validating inputs is usually the first layer of defense. Sanitizing consists of removing any unsafe character from user inputs, and validating will check if the data is in the expected format and type.
Sanitizing inputs From the user s browser, data input travels through GET request, POST request, and cookies, which hackers can edit, modify, and manipulate to gain access to the web server. Input sanitization serves as a strainer to filter encoded data as it moves into the web server.
Actually, I wrote a package to solve this problem easily. You can use it or contribute to it on Github.
Download this package from here: https://www.npmjs.com/package/string-sanitizer
You can use this utility package to sanitize even foreign languages other than English. Under the hood, regex is used in this library. You can convert your string to URL or filename friendly string. The use cases are given below
var string = require("string-sanitizer"); string.sanitize("a.bc@d efg#h"); // abcdefgh string.sanitize.keepSpace("a.bc@d efg#h"); // abcd efgh string.sanitize.keepUnicode("a.bc@d efg#hক"); // abcd efghক string.sanitize.addFullstop("a.bc@d efg#h"); // abcd.efgh string.sanitize.addUnderscore("a.bc@d efg#h"); // abcd_efgh string.sanitize.addDash("a.bc@d efg#h"); // abcd-efgh string.sanitize.removeNumber("@abcd efgh123"); // abcdefgh string.sanitize.keepNumber("@abcd efgh123"); // abcdefgh123 string.addFullstop("abcd efgh"); // abcd.efgh string.addUnderscore("@abcd efgh"); // @abcd_efgh string.addDash("@abcd efgh"); // @abcd-efgh string.removeSpace("@abcd efgh"); // @abcdefgh
Codeblock
For most of the framework, you can use sanitize
node module:
npm install sanitize --save
And 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 options
validate(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 : {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With