Using express-validator for Request Validation

PHOTO EMBED

Fri Apr 14 2023 09:18:26 GMT+0000 (Coordinated Universal Time)

Saved by @mindplumber #javascript #uuid #guid

const express = require('express');
const { body, sanitizeBody, validationResult } = require('express-validator');

const app = express();

app.use(express.json());

// Define a route handler that uses request validation middleware
app.post('/register',
  body('username').trim().isLength({ min: 3, max: 30 })
    .withMessage('Username must be between 3 and 30 characters long')
    .escape(),
  body('email').trim().isEmail()
    .withMessage('Please enter a valid email address')
    .normalizeEmail(),
  body('password').isLength({ min: 6 })
    .withMessage('Password must be at least 6 characters long')
    .matches(/\d/)
    .withMessage('Password must contain at least one number')
    .customSanitizer((value, { req }) => {
      // Hash the password before storing it in the database
      const hashedPassword = hashPassword(value);
      req.body.password = hashedPassword;
      return hashedPassword;
    }),
  (req, res) => {
    // Check for validation errors
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
    }

    // Sanitize input data
    sanitizeBody('username').escape();
    sanitizeBody('email').normalizeEmail();

    // Registration logic here
    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;
    const message = `Registered user: ${username} (${email}, ${password})`;
    res.send(message);
  });

// Start the server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});
content_copyCOPY

We define a route handler for a `POST /register` endpoint that uses the `body()` method from express-validator to define validation rules for the `username`, `email`, and `password` request parameters. We also use the `withMessage()` method to define custom error messages for each rule. We then use the `normalizeEmail()` method to sanitize the `email` parameter, and the `trim()` method to sanitize the username parameter. If there are no validation errors, we proceed with the registration logic and send a success response. We define a custom sanitizer for the password parameter using the `customSanitizer()` method. This sanitizer hashes the password before storing it in the database, and updates the request body with the hashed value. We also use the `sanitizeBody()` method to sanitize the username and email parameters by escaping special characters and normalizing email addresses. Note that this is still a simplified example - express-validator provides many more options and features for complex sanitization and data validation.