Skip to content

Backend Input Validation — Comprehensive Input Validation for APIs

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Backend Input Validation. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Input validation prevents injection attacks, data corruption, and unexpected behavior by ensuring all inputs conform to expected formats.

const Joi = require('joi');

// Schema validation middleware
function validate(schema) {
  return (req, res, next) => {
    const { error, value } = schema.validate(req.body, {
      abortEarly: false,
      stripUnknown: true,
      allowUnknown: false
    });

    if (error) {
      const errors = error.details.map(d => ({
        field: d.path.join('.'),
        message: d.message,
        type: d.type
      }));

      return res.status(400).json({
        error: 'VALIDATION_ERROR',
        message: 'Request validation failed',
        details: errors
      });
    }

    req.body = value;
    next();
  };
}

// Validation schemas
const scanRequestSchema = Joi.object({
  fileName: Joi.string()
    .pattern(/^[\w\-. ]+$/)
    .max(255)
    .required()
    .messages({
      'string.pattern.base': 'File name contains invalid characters'
    }),
  fileContent: Joi.string()
    .base64()
    .max(10 * 1024 * 1024) // 10MB
    .required(),
  scanType: Joi.string()
    .valid('quick', 'deep', 'full')
    .default('quick'),
  metadata: Joi.object({
    source: Joi.string().max(100),
    tags: Joi.array().items(Joi.string().max(50)).max(10)
  })
});

app.post('/api/scans', validate(scanRequestSchema), scanHandler);

// Sanitization middleware
const sanitizeHtml = require('sanitize-html');
function sanitizeInput(req, res, next) {
  for (const [key, value] of Object.entries(req.body)) {
    if (typeof value === 'string') {
      req.body[key] = sanitizeHtml(value, {
        allowedTags: [],
        allowedAttributes: {}
      });
    }
  }
  next();
}

Comprehensive input validation is the first line of defense against injection and data corruption attacks.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro