0
0
Node.jsframework~5 mins

Request validation in Node.js

Choose your learning style9 modes available
Introduction

Request validation helps check if the data sent to your server is correct and safe before using it.

When a user submits a form with their name and email.
When an API receives data from another app and needs to check it.
When you want to make sure numbers or dates sent are in the right format.
When you want to avoid errors caused by missing or wrong data.
When you want to protect your app from bad or harmful input.
Syntax
Node.js
import express from 'express';
import { body, validationResult } from 'express-validator';

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

app.post('/route', [
  body('fieldName').validationMethod(),
  // more validations
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  // handle valid data
  res.send('Success');
});

Use express-validator package to add validation rules easily.

Always check validationResult to find errors before processing data.

Examples
Checks if the 'email' field contains a valid email address.
Node.js
body('email').isEmail()
Checks if the 'age' field is an integer and at least 18.
Node.js
body('age').isInt({ min: 18 })
Checks if the 'password' field has at least 6 characters.
Node.js
body('password').isLength({ min: 6 })
Checks if the 'username' field is not empty.
Node.js
body('username').notEmpty()
Sample Program

This code creates a simple server that checks if the username is not empty, the email is valid, and the password is at least 6 characters long before accepting the registration.

Node.js
import express from 'express';
import { body, validationResult } from 'express-validator';

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

app.post('/register', [
  body('username').notEmpty(),
  body('email').isEmail(),
  body('password').isLength({ min: 6 })
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send('User registered successfully');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always validate user input to avoid crashes and security issues.

Use clear error messages to help users fix their input.

Validation runs before your main code, so bad data never reaches your logic.

Summary

Request validation checks data before using it.

Use express-validator for easy rules in Node.js.

Always handle validation errors to keep your app safe and stable.