Validación de datos que llegan al API REST en NodeJS

En express.js podemos utilizar validator.js

Instalar con: $ npm install –save express-validator

Por ejemplo tenemos este codigo para crear nuevo usuario:

const express = require('express');
const app = express();

app.use(express.json());
app.post('/user', (req, res) => {
  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});

Antes de crear usuario nuevo con el POST podemos verificar los datos:

// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator/check');

app.post('/user', [
  // username must be an email
  check('username').isEmail(),
  // password must be at least 5 chars long
  check('password').isLength({ min: 5 })
], (req, res) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }

  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});

Ahora si hay problemas en validación, tendremos de respuesta:

{
  "errors": [{
    "location": "body",
    "msg": "Invalid value",
    "param": "username"
  }]
}

Mas información en https://express-validator.github.io/docs/

Leave a Reply

Your email address will not be published. Required fields are marked *