express class validator

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

const app = express();

app.use(express.json());

app.post(
  '/user',
  [
    body('username').isEmail(),
    body('password').isLength({ min: 5 }),
    body('confirmPassword').custom((value, { req }) => {
      if (value !== req.body.password) {
        throw new Error('Password confirmation does not match password');
      }
      return true;
    }),
  ],
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    // Logic to handle valid user data

    res.json({ success: true });
  }
);

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Explanation:

  1. Import the necessary modules: express for creating the server, and body and validationResult from express-validator for handling request body validation.

  2. Create an instance of the Express application.

  3. Use express.json() middleware to parse incoming JSON requests.

  4. Define a POST route at the path '/user' that handles user registration.

  5. Utilize the body function from express-validator to define validation checks for the 'username', 'password', and 'confirmPassword' fields in the request body.

  6. Use the isEmail validator to check if the 'username' field is a valid email.

  7. Use the isLength validator to check if the 'password' field has a minimum length of 5 characters.

  8. Use the custom validator for the 'confirmPassword' field to check if it matches the 'password' field.

  9. In the route handler function, use validationResult to check for validation errors. If errors are present, return a 400 status with the error details.

  10. If there are no validation errors, proceed with the logic to handle the valid user data. In this example, a success JSON response is sent.

  11. Set up the server to listen on the specified port (either from the environment variable or default to 3000) and log a message indicating the server is running.