0
0
Expressframework~5 mins

Why input validation is critical in Express

Choose your learning style9 modes available
Introduction

Input validation helps make sure the data your app gets is safe and correct. It stops bad or wrong data from causing problems.

When users fill out forms on your website
When your app receives data from other apps or services
When saving data to a database to keep it clean
When you want to protect your app from hackers trying to send harmful data
Syntax
Express
app.post('/route', (req, res) => {
  const { name, age } = req.body;
  if (!name || typeof name !== 'string') {
    return res.status(400).send('Name is required and must be a string');
  }
  if (age === undefined || typeof age !== 'number') {
    return res.status(400).send('Age is required and must be a number');
  }
  // continue processing
  res.send('Data is valid');
});
Always check the type and presence of required fields.
Send clear error messages to help users fix their input.
Examples
This example checks if the email exists and contains '@' to be a simple valid email.
Express
app.post('/signup', (req, res) => {
  const { email } = req.body;
  if (!email || !email.includes('@')) {
    return res.status(400).send('Valid email is required');
  }
  res.send('Signup data is valid');
});
This example converts age to a number and checks if the user is at least 18.
Express
app.post('/age-check', (req, res) => {
  const age = Number(req.body.age);
  if (!age || age < 18) {
    return res.status(400).send('You must be 18 or older');
  }
  res.send('Age is valid');
});
Sample Program

This Express app listens for POST requests to '/register'. It checks if username is a string and password is at least 6 characters. If validation fails, it sends an error. Otherwise, it confirms the data is valid.

Express
import express from 'express';
const app = express();
app.use(express.json());

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

  if (!username || typeof username !== 'string') {
    return res.status(400).send('Username is required and must be a string');
  }

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

  res.send('Registration data is valid');
});

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

Always validate input on the server, even if you check it on the client.

Use clear error messages to help users fix mistakes.

Input validation helps protect your app from security risks like injections.

Summary

Input validation keeps your app safe and working well.

Check data types and required fields before using input.

Send helpful error messages when input is wrong.