简体   繁体   English

在Node.Js中的express-validator之前修剪输入值

[英]Trim input values before express-validator in Node.Js

I'm using the suggested V4 syntax of express-validator in a Node.js project: 我在Node.js项目中使用了建议的express-validator V4语法:

const { check, validationResult } = require('express-validator/check');
const { matchedData } = require('express-validator/filter');

and

app.post('/users/add/',[
check('first_name')
.isLength({ min: 1 }).withMessage('A first name is required')],
(req, res, next) => {
  var errors = validationResult(req);
  if (errors) {
     ..etc

Note that I am using the modern syntax and do not have the following code (as per the express-validator README.md file): 请注意,我使用的是现代语法,没有以下代码(根据express-validator README.md文件):

const expressValidator = require('express-validator');
app.use(expressValidator());

How do I trim blank spaces from the input field before running the validation? 在运行验证之前,如何在输入字段中修剪空格?

You should use .trim() before your .check() like this, 您应该使用.trim()你之前.check()这样的,

check('first_name').trim().isLength({ min: 1 }).withMessage('A first name is required')]

Hope this helps! 希望这可以帮助!

The following work around may help, though I think the best solution would be to support sanitation in a fluent manner. 尽管我认为最好的解决方案是以流畅的方式支持卫生,但以下解决方法可能会有所帮助。 The downside of my work around is that the processing of input is now in two places. 我的工作的缺点是,现在在两个地方处理输入。

  1. Add the required sanitation functions to requires clause: 在require子句中添加所需的卫生功能:

     const { trim } = require('express-validator').validator 
  2. Adjust the request processing: 调整请求处理:

     app.post('/users/add/', (req, res, next) => { req.body.first_name = trim(req.body.first_name); req.body.last_name = trim(req.body.last_name); req.body.email = trim(req.body.email); next(); }, [check('first_name') .isLength({ min: 1 }).withMessage('A first name is required')], (req, res, next) => { var errors = validationResult(req); if (errors) { ..etc 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM