JAVASCRIPT

Robust Server-Side Input Validation for JSON Payloads

Ensure data integrity and prevent various injection attacks by implementing comprehensive server-side input validation for all incoming request payloads.

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

const app = express();
app.use(express.json()); // Middleware to parse JSON request bodies

app.post('/register', [
  // Validate 'username': must be a string, min 3 chars, max 20, alphanumeric
  body('username').isString().trim().isLength({ min: 3, max: 20 }).withMessage('Username must be 3-20 alphanumeric characters').matches(/^[a-zA-Z0-9]+$/),

  // Validate 'email': must be a valid email format
  body('email').isEmail().normalizeEmail().withMessage('Invalid email address'),

  // Validate 'password': min 8 chars, contains at least one uppercase, one lowercase, one number, one special char
  body('password').isString().isLength({ min: 8 }).withMessage('Password must be at least 8 characters long')
    .matches(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).*$/)
    .withMessage('Password must include uppercase, lowercase, number, and special character'),

  // Validate 'age': must be an integer between 18 and 120
  body('age').isInt({ min: 18, max: 120 }).withMessage('Age must be between 18 and 120'),

], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  // If validation passes, process the data (e.g., save to database)
  const { username, email, age } = req.body;
  res.status(200).json({ message: 'User registered successfully', user: { username, email, age } });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: Server-side input validation is critical for securing web applications, as client-side validation can be bypassed by malicious actors. This snippet demonstrates robust server-side validation using `express-validator` in a Node.js (Express) application. It checks for data types, lengths, specific formats (like email and complex password patterns), and ranges (like age) for an incoming JSON payload. If any validation rule fails, it returns a 400 Bad Request error with detailed error messages, preventing malformed or malicious data from reaching the application's core logic or database.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs