Javascript 如何清理节点 js 中的输入值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46718772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How I can sanitize my input values in node js?
提问by V.Aleksanyan
I validated my Node.js inputs so that they won't be empty, but I want sanitize them too. Please help me how I can do this.
我验证了我的 Node.js 输入,以便它们不会为空,但我也想对它们进行消毒。请帮助我如何做到这一点。
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);
}
回答by kgangadhar
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 sanitizedocumentation
If you are using
express, then you can validate and sanitize using built-in express functionalities as follows:const express = require('express') 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-validatorand express-sanitize-inputdocumentation.
If you are using
Hapi, then you can validate and sanitize using Joi, With the Joi you can sanitize variable with addition optionsvalidate(value, schema, {escapeHtml: true}, [callback])For more can go through Joidocumentation.
If you don't want to use any third party module and want to sanitize using the build-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 !== null ? obj : {};
对于大多数框架,您可以使用
sanitizenode 模块:npm install sanitize --save然后可以使用像:
var sanitizer = require('sanitize')(); var name = sanitizer.value(req.name, 'string'); var surname= sanitizer.value(req.surname, 'string');有关更多信息,请参阅 sanitize文档
如果您正在使用
express,那么您可以使用内置的 express 功能进行验证和清理,如下所示:const express = require('express') 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 })如需更多信息,请参阅express-validator和express-sanitize-input文档。
如果您正在使用
Hapi,那么您可以使用Joi进行验证和清理,使用 Joi 您可以使用附加选项清理变量validate(value, schema, {escapeHtml: true}, [callback])更多内容可以查看Joi文档。
如果您不想使用任何第三方模块并希望使用内置节点进行清理。您可以尝试以下操作:
// 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 !== null ? obj : {};
回答by Md Fazlul Karim
Actually, I wrote a package to solve this problem easily. You can use it or contribute to it on Github.
其实,我写了一个包来轻松解决这个问题。你可以使用它或在 Github 上贡献它。
Download this package from here: https://www.npmjs.com/package/string-sanitizer
从这里下载这个包: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
您甚至可以使用此实用程序包来清理除英语之外的外语。在幕后,这个库中使用了正则表达式。您可以将字符串转换为 URL 或文件名友好字符串。用例如下
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


