0
0
Expressframework~5 mins

express-validator setup

Choose your learning style9 modes available
Introduction

express-validator helps check and clean user input in Express apps. It keeps your app safe and error-free.

When you want to check if a user typed a valid email in a signup form.
When you need to make sure a password is strong enough before saving it.
When you want to confirm required fields are not empty in a form submission.
When you want to give clear error messages if user input is wrong.
When you want to avoid bad data causing bugs or security issues.
Syntax
Express
import { body, validationResult } from 'express-validator';

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() });
  }
  // proceed if no errors
});

Use body() to check data sent in the request body.

validationResult(req) collects errors after validations run.

Examples
Checks if the 'email' field contains a valid email address.
Express
body('email').isEmail()
Ensures the 'password' field is at least 6 characters long.
Express
body('password').isLength({ min: 6 })
Checks that the 'username' field is not empty.
Express
body('username').notEmpty()
Sample Program

This Express app sets up a POST route '/register' that checks user input for email, password, and username. If input is invalid, it sends back error details. If all is good, it confirms registration.

Express
import express from 'express';
import { body, validationResult } from 'express-validator';

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

app.post('/register', [
  body('email').isEmail().withMessage('Enter a valid email'),
  body('password').isLength({ min: 6 }).withMessage('Password must be 6+ chars'),
  body('username').notEmpty().withMessage('Username is required')
], (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 port 3000'));
OutputSuccess
Important Notes

Always call validationResult(req) inside your route handler to get validation errors.

You can chain withMessage() to customize error messages for each check.

express-validator works well with Express JSON middleware to parse request bodies.

Summary

express-validator helps check and clean user input in Express apps.

Use body() and other validators to define rules for input fields.

Check errors with validationResult(req) and respond accordingly.