Data Validation and Sanitization

6 min read

Never Trust the Client: Why Validation Matters

Definition:

  • Validation is the process of checking if the incoming data meets expected formats, types, and constraints (e.g., ensuring a string looks like an email).
  • Sanitization is the process of cleaning or modifying the incoming data to remove unwanted or dangerous characters (e.g., removing HTML tags from a text input).

The Problem:
When you build an API, your server opens a door to the internet. If you expect a user to send their age as a number, an honest user might accidentally send the word "twenty". A malicious user might send a snippet of JavaScript code to see if your server will execute it. If you process this data blindly, your server might crash, corrupt your database, or leak sensitive data to hackers.

Imagine you are running a pizza shop (the server). You have customers (requests) coming in constantly. If a customer orders "-5 pizzas" and you just process it without checking, your inventory math will break. If a customer names themselves "Give me all the money in the register" and you write that blindly on the receipt, chaos ensues. You need a bouncer at the front door checking IDs and standardizing orders before they reach the kitchen.

The Solution:
By enforcing strict data validation and sanitization rules on incoming requests, you catch errors before they touch your core application logic or database.


Validating Request Data with express-validator or Joi

In the Node.js industry, there are two dominant tools used to solve the validation problem: express-validator and Joi.

1. express-validator (The Middleware Approach)

express-validator is a set of Express.js middleware that wraps validator.js. It allows you to chain validation rules directly in your route definitions.

Setup:

bash
npm install express-validator

Usage:
Let's validate a user registration route. We want to ensure the email is valid and the password is at least 6 characters long.

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

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

// Array of validation middlewares
const registerValidationRules = [
  body('email').isEmail().withMessage('Please provide a valid email address'),
  body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long')
];

app.post('/register', registerValidationRules, (req, res) => {
  // Extract validation errors from the request
  const errors = validationResult(req);
  
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  // If no errors, proceed with registration logic
  res.status(201).json({ message: 'User registered successfully!' });
});

Under the hood: express-validator inspects the req.body object, runs the validation functions against the specified keys, and attaches any failures to a hidden property on the req object. The validationResult(req) function then extracts those errors.

2. Joi (The Schema Approach)

Joi is a powerful schema description language and data validator. Instead of attaching rules to the route, you create a standalone "blueprint" (schema) of what your data should look like, and then test your request data against it.

Setup:

bash
npm install joi

Usage:

javascript
const express = require('express');
const Joi = require('joi');

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

// Define a schema blueprint
const userSchema = Joi.object({
  email: Joi.string().email().required(),
  password: Joi.string().min(6).required()
});

app.post('/login', (req, res) => {
  // Validate the request body against the schema
  const { error, value } = userSchema.validate(req.body);

  if (error) {
    // Send back the first error message
    return res.status(400).json({ error: error.details[0].message });
  }

  // Proceed with validated 'value'
  res.status(200).json({ message: 'Login successful!' });
});

Which one should you use?

  • Use express-validator if you want seamless middleware integration right inside your Express routes and built-in sanitization.
  • Use Joi if you prefer keeping your validation logic decoupled from Express, or if you have complex, deeply nested JSON objects to validate.

Sanitizing Inputs to Prevent Injection Attacks

The Problem:
Validation checks if data is correct, but it doesn't clean it. If a user submits a blog comment containing <script>alert('Hacked!');</script>, and you save it directly to your database, anyone who views that comment will unknowingly execute the malicious script on their computer. This is known as Cross-Site Scripting (XSS).

The Solution:
Sanitization mutates the data, stripping out dangerous characters or converting them into harmless text (HTML escaping).

express-validator makes sanitization incredibly easy because you can chain sanitizers directly after your validators.

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

app.post('/comment', [
  body('text')
    .notEmpty().withMessage('Comment cannot be empty')
    .trim()     // Removes whitespace from the beginning and end
    .escape(),  // Converts <, >, &, ', ", and / to HTML entities
  
  body('email')
    .isEmail()
    .normalizeEmail() // Converts e.g. [email protected] to [email protected]
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });

  // Industry Standard: Extract ONLY validated and sanitized data
  const safeData = matchedData(req);
  
  // safeData.text is now perfectly safe to store in the database!
  res.json({ data: safeData });
});

Interesting Fact: Why use matchedData()? Imagine an attacker sends {"text": "Hello", "adminRole": true} in their request. Even if you validate text, if you blindly insert req.body into your database, you might accidentally give them full admin privileges! matchedData(req) acts like a strict bouncer—it strips away any fields that weren't explicitly validated, dropping the malicious adminRole entirely. 🛡️


Returning Meaningful Validation Errors to the User

The Problem:
When validation fails, backend servers often throw generic 500 Internal Server Error messages or completely silent 400 Bad Request statuses. If you are a frontend developer (or an end-user filling out a long form), a message like "Error: [Object object]" or "Validation Failed" is completely useless. You need to know which field failed and why.

The Solution:
Always return a structured, predictable error payload.

Here is an industry-standard way to return meaningful validation errors using a reusable middleware.

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

// Reusable error handling middleware
const validateRequest = (req, res, next) => {
  const errors = validationResult(req);
  
  if (!errors.isEmpty()) {
    // Format the errors into a clean, readable array of objects
    const formattedErrors = errors.array().map(err => ({
      field: err.path,       // The field that failed (e.g., 'age')
      message: err.msg       // The reason it failed
    }));

    return res.status(400).json({
      status: 'error',
      errors: formattedErrors
    });
  }
  
  // If no errors, pass control to the next route handler
  next();
};

// Usage in a route:
app.post('/profile', [
  body('username').isAlphanumeric().withMessage('Username must be letters and numbers only'),
  body('age').isInt({ min: 18 }).withMessage('Must be at least 18 years old')
], validateRequest, (req, res) => {
  res.json({ message: "Profile updated successfully!" });
});

If a user sends an invalid age, your API will respond with this beautiful, easy-to-parse JSON:

json
{
  "status": "error",
  "errors": [
    {
      "field": "age",
      "message": "Must be at least 18 years old"
    }
  ]
}

Now the frontend code can seamlessly map over the errors array and display the exact red warning text underneath the specific input field on the user's screen.


References

Challenge

User Registration Endpoint Validation

You are tasked with securing a new user registration endpoint (/register) in an Express.js application. Your goal is to implement a complete validation and sanitization middleware chain using express-validator.

Implement the middleware to enforce the following rules on the incoming request body:

  1. email:
    • Must be a valid email address.
    • Should be normalized (e.g., convert to lowercase).
  2. username:
    • Must not be empty.
    • Must be between 4 and 20 characters long.
    • Must be trimmed of leading/trailing whitespace.
    • Must have HTML special characters escaped.
  3. password:
    • Must be at least 8 characters long.
    • Must contain at least one number and one special character. You can use .matches() with a regular expression for this. (Hint: /(?=.*\d)(?=.*[!@#$%^&*])/)
  4. bio (Optional Field):
    • If present, it should be escaped to prevent XSS attacks.

After the validation chain, complete the route handler logic:

  • Check for validation errors using the appropriate function.
  • If errors exist, send a 400 Bad Request response with a JSON body containing a key errors which is an array of the validation errors.
  • If the data is valid, use the security best practice to extract only the validated and sanitized data from the request.
  • Send a 201 status code with a JSON response containing the cleaned, validated data.

Expected result

Your final code should correctly define an array registrationValidationChain containing a series of chained body() calls from express-validator.

  • The email field should use .isEmail() and .normalizeEmail().
  • The username field should use .notEmpty(), .isLength({ min: 4, max: 20 }), .trim(), and .escape().
  • The password field should use .isLength({ min: 8 }) and .matches() with the specified regex.
  • The bio field should be marked as .optional() and use .escape().

Inside the route handler for app.post('/register', ...):

  1. It must call validationResult(req) to check for errors.
  2. If !result.isEmpty(), it must respond with res.status(400).json({ errors: result.array() }).
  3. If validation passes, it must call matchedData(req) to get the sanitized data.
  4. It must then respond with res.status(201).json(validatedData) where validatedData is the result from matchedData.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.