0
0
Expressframework~5 mins

Validating body fields in Express

Choose your learning style9 modes available
Introduction

We check the data sent by users to make sure it is correct and safe before using it.

When a user submits a form with information like name or email.
When your app receives data to create or update something in the database.
When you want to prevent wrong or harmful data from entering your system.
Syntax
Express
app.post('/route', (req, res) => {
  const { field } = req.body;
  if (!field) {
    return res.status(400).send('Field is required');
  }
  // continue processing
});
Use req.body to access data sent in the request body.
Always send a clear error message if validation fails.
Examples
Checks if the email field is present before continuing.
Express
app.post('/signup', (req, res) => {
  const { email } = req.body;
  if (!email) {
    return res.status(400).send('Email is required');
  }
  res.send('Signup successful');
});
Validates that both username and password are provided.
Express
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) {
    return res.status(400).send('Username and password are required');
  }
  res.send('Login successful');
});
Ensures quantity is a positive number before proceeding.
Express
app.post('/order', (req, res) => {
  const { quantity } = req.body;
  if (typeof quantity !== 'number' || quantity <= 0) {
    return res.status(400).send('Quantity must be a positive number');
  }
  res.send('Order placed');
});
Sample Program

This Express app listens for POST requests to /register. It checks if the username and password are sent and if the password is long enough. If any check fails, it sends an error message. Otherwise, it confirms registration.

Express
import express from 'express';

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

app.post('/register', (req, res) => {
  const { username, password } = req.body;

  if (!username) {
    return res.status(400).send('Username is required');
  }

  if (!password) {
    return res.status(400).send('Password is required');
  }

  if (password.length < 6) {
    return res.status(400).send('Password must be at least 6 characters');
  }

  res.send(`User ${username} registered successfully`);
});

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

Always use express.json() middleware to parse JSON body data.

Validation helps keep your app safe and working well.

For complex validation, consider libraries like Joi or express-validator.

Summary

Check user data in req.body before using it.

Send clear error messages if data is missing or wrong.

Use middleware to parse JSON body data.