0
0
Node.jsframework~5 mins

Input validation and sanitization in Node.js

Choose your learning style9 modes available
Introduction

Input validation and sanitization help keep your app safe and working right by checking and cleaning user data before using it.

When users fill out forms on your website or app
When receiving data from external sources like APIs
Before saving user input to a database
When processing data that affects app behavior or security
Syntax
Node.js
import { body, validationResult } from 'express-validator';

app.post('/submit', [
  body('email').isEmail().normalizeEmail(),
  body('age').isInt({ min: 0 })
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  // Use sanitized and validated data here
  res.send('Data is valid and safe!');
});

Use express-validator middleware to validate and sanitize inputs in Node.js apps.

Always check validationResult to handle errors before using data.

Examples
Removes extra spaces and escapes harmful characters from a username input.
Node.js
body('username').trim().escape()
Checks if the input is a valid email and cleans it to a standard format.
Node.js
body('email').isEmail().normalizeEmail()
Validates that age is a whole number between 0 and 120.
Node.js
body('age').isInt({ min: 0, max: 120 })
Sample Program

This Node.js app uses Express and express-validator to check and clean user input for username, email, and age. If input is bad, it sends errors. If good, it welcomes the user with their cleaned data.

Node.js
import express from 'express';
import { body, validationResult } from 'express-validator';

const app = express();
app.use(express.json());

app.post('/register', [
  body('username').trim().escape(),
  body('email').isEmail().normalizeEmail(),
  body('age').isInt({ min: 0, max: 120 })
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send(`Welcome, ${req.body.username}! Your email is ${req.body.email} and age is ${req.body.age}.`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always validate and sanitize inputs to avoid security risks like injection attacks.

Use libraries like express-validator to simplify input checks.

Test your validation by sending different inputs using tools like Postman or browser DevTools.

Summary

Input validation checks if data is correct and safe.

Sanitization cleans data to remove harmful parts.

Use middleware like express-validator in Node.js for easy validation and sanitization.