简体   繁体   中英

Trim input values before express-validator in Node.Js

I'm using the suggested V4 syntax of express-validator in a Node.js project:

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):

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,

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:

     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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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