JAVASCRIPT

Implement Robust Input Schema Validation with Joi

Ensure data integrity and security by validating incoming API request bodies against predefined schemas using the Joi library in Node.js applications.

// Install: npm install joi
const Joi = require('joi');

// Define a schema for user registration data
const userSchema = Joi.object({
  username: Joi.string().alphanum().min(3).max(30).required(),
  email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } }).required(),
  password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(), // Example, stronger patterns recommended
  birthYear: Joi.number().integer().min(1900).max(new Date().getFullYear()).optional()
});

// Middleware for Express to validate request body
const validate = (schema, property) => (req, res, next) => {
  const { error } = schema.validate(req[property]);
  if (error) {
    const { details } = error;
    const message = details.map(i => i.message).join(',');
    console.log("Validation Error:", message);
    return res.status(400).json({ error: message });
  }
  next();
};

// Example usage in an Express route
/*
const express = require('express');
const app = express();
app.use(express.json());

app.post('/register', validate(userSchema, 'body'), (req, res) => {
  // If validation passes, req.body is safe to use
  res.status(200).json({ message: 'User registered successfully!' });
});

app.listen(3000, () => console.log('Server running on port 3000'));
*/
How it works: This snippet demonstrates robust server-side input validation using the Joi library in a Node.js Express application. It defines a schema that specifies the expected data types, formats, lengths, and constraints for incoming request properties (like `username`, `email`, `password`). A reusable middleware function `validate` then applies this schema to `req.body` (or `req.query`, `req.params`) and sends a 400 Bad Request error if validation fails, preventing malformed or malicious data from reaching your application 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