Javascript 如何清理节点js中的输入值?

Javascript 如何清理节点js中的输入值?,javascript,node.js,sanitization,Javascript,Node.js,Sanitization,我验证了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', 'Pa

我验证了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);
}
  • 对于大多数框架,您可以使用节点模块:

     npm install sanitize --save
    
    然后可以使用类似于:

     var sanitizer = require('sanitize')();
    
     var name = sanitizer.value(req.name, 'string');
     var surname= sanitizer.value(req.surname, 'string');
    
    有关更多信息,请参阅文档

  • 如果您使用的是
    express
    ,则可以使用和包进行验证和消毒,如下所示:

     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
     })  
    
    如需了解更多信息,请浏览和查阅文档

  • 如果您使用的是
    Hapi
    ,那么您可以使用Joi验证和清理变量,使用其他选项清理变量

     validate(value, schema, {escapeHtml: true}, [callback])
    
    有关更多信息,请参阅文档

  • 如果您不想使用任何第三方模块,并且想使用内置节点进行清理。您可以尝试以下操作:

     // 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 : {};
    

事实上,我写了一个软件包来轻松解决这个问题。您可以在Github上使用它,也可以为它做贡献

从此处下载此软件包:

您可以使用此实用程序包对英语以外的外语进行清理。在后台,这个库使用正则表达式。您可以将字符串转换为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


您可以始终使用及其模型层来定义验证。也许您可以使用:您可以使用joi framework.@V.Aleksanyan,这里的
字符串
指您想要匹配的值或您想要允许的正则表达式。当我提交表单I check validation并编写代码var name=sanitizer.value(req.body.name,'string')时,您可以在中尝试这一点;var name=sanitizer.value(req.body.name,'string');var name=sanitizer.value(req.body.username,'string');它返回我这个错误“字符串不是有效的消毒剂类型”。请告诉我这是为什么?这只是一个演示其工作原理的示例,应该是这样的
var myMatchingString=sanitizer.value(req.mystring,/abc123/)或正则表达式而不是
abc123
,通读一遍,它将解释如何使用应用程序作为中间件
check()
不是Express内置的。这是@sloreti的一部分,谢谢你的更新!该库更类似于字符串操作库,而不是可行的消毒剂。卫生设施应该设法包含输入,最好是上下文感知的,而不仅仅是将字符串操纵到某个假定的期望结果:
string.sanitize(“1@2.com“”
在理想情况下不会返回
“12com”
。一些改进可能包括关注特定于上下文的环境卫生(
sanitize.HTMLsafe()
sanitize.SQLsafe()
sanitize.EmailAddress()
,等等),以及删除字符串帮助函数(将厨房水槽留在家中)。感谢您的建议。基本上,我写它是为了解决一个实际问题。从那时起,许多人觉得它方便和有用。“消毒剂”在我们的实际生活中是指清洁或消毒。“消毒剂”一词就是在这个实际意义上使用的。没别的了。此外,在发布此库时,名称字符串操纵器和字符串操纵器都已被采用。我将尝试在将来添加这些更新。再次谢谢你。