← Back to all snippets
JAVASCRIPT

Performing Robust Server-Side Input Validation (Node.js)

Implement robust server-side input validation using `express-validator` to ensure data integrity and prevent security vulnerabilities from malformed or malicious user inputs.

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

const app = express();
app.use(express.json()); // For parsing application/json
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded

app.post('/register', [
  // Validate and sanitize username
  body('username')
    .trim()
    .isLength({ min: 3 }).withMessage('Username must be at least 3 characters long')
    .matches(/^[a-zA-Z0-9_]+$/).withMessage('Username can only contain letters, numbers, and underscores'),

  // Validate password
  body('password')
    .isLength({ min: 8 }).withMessage('Password must be at least 8 characters long')
    .matches(/[a-z]/).withMessage('Password must contain a lowercase letter')
    .matches(/[A-Z]/).withMessage('Password must contain an uppercase letter')
    .matches(/[0-9]/).withMessage('Password must contain a number')
    .matches(/[^a-zA-Z0-9]/).withMessage('Password must contain a special character'),

  // Validate email
  body('email')
    .isEmail().withMessage('Invalid email address')
    .normalizeEmail()

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

  // If validation passes, process the data
  const { username, email, password } = req.body;
  // In a real application: hash password, save user to DB, etc.
  res.status(200).json({ message: 'User registered successfully!', user: { username, email } });
});

app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This Node.js Express snippet demonstrates robust server-side input validation using `express-validator`. It defines a set of validation rules for `username`, `password`, and `email` fields. These rules check for length, character sets, email format, and password complexity. If any validation fails, `validationResult(req)` captures the errors, which are then returned to the client with a 400 status. This prevents malformed or malicious data from reaching the backend logic or database, crucial for security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs