0

I am using Postman to test the API that handles form submissions for my web application, but I am getting the wrong response for my firstName and lastName sections. Regardless of what I input in these sections. Even if I leave them empty or just input # value for firstName and @ value for lastName, I keep getting 200 OK Form submitted successfully. However, I want it to send a 400 Bad request if the firstName or lastName is less than two characters each, and includes anything other than letters. For my email and message sections, those are working correctly. I only have problems with firstName and lastName.

This is what I have for my code:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true })); // Use body-parser middleware to parse request     bodies

// Serve static files from the public directory
app.use(express.static('public'));

// Parse incoming form submissions
app.use(express.urlencoded({ extended: true }));

// Handle form submission
app.post(
    '/submit-form',
    [
      body('firstName')
        .isAlpha()
        .isLength({ min: 2 })
        .withMessage('First name must be at least 2 letters and contain only letters.'),
      body('lastName')
        .isAlpha()
        .isLength({ min: 2 })
        .withMessage('Last name must be at least 2 letters and contain only letters.'),
      body('email')
        .isEmail()
        .withMessage('Invalid email format.'),
      body('message')
        .trim()
        .notEmpty()
        .withMessage('Message cannot be empty.'),
    ],
     (req, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }

      const firstName = req.body.firstName;
      const lastName = req.body.lastName;
      const email = req.body.email;
      const message = req.body.message;

  // Send a response back to the client
  res.status(200).send('Form submitted successfully');
});

// Route to display a confirmation message
app.get('/confirmation', (req, res) => {
    // Code to display confirmation message 
    res.status(200).send('Thank you for submitting the form!');
});

// Start server
app.listen(3000, () => console.log('Server started on port 3000'));
Christian Baumann
  • 3,188
  • 3
  • 20
  • 37
jjc
  • 1
  • Where is this "body" in `body('firstName')` coming from? – tjarbo Feb 22 '23 at 07:35
  • Could u also please share your Postman request as a curl command or even better as HTTP request? https://stackoverflow.com/a/60147919 – tjarbo Feb 22 '23 at 07:37
  • Don't forget the `app.use(express.json())` middleware – lpizzinidev Feb 22 '23 at 07:51
  • @tjarbo it's coming from the 'express validator' package that was imported at the top of my code: const { body, validationResult } = require('express-validator'); – jjc Feb 22 '23 at 21:46
  • @lpizzinidev I used that first but it kept giving me the same thing so I decided to replace it with this body-parser line: app.use(bodyParser.urlencoded({ extended: true })); – jjc Feb 22 '23 at 21:50

1 Answers1

0

You need to add the app.use(express.json()) middleware to parse incoming requests to JSON.

Also, body-parser is deprecated, and you should use only app.use(express.urlencoded({ extended: true }));.

For the validator, try to specify a custom one:

const express = require('express');
const app = express();
const port = 3000;

// Serve static files from the public directory
app.use(express.static('public'));

// Parse incoming form submissions
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Handle form submission
app.post(
    '/submit-form',
    [
      body('firstName')
        .trim()
        .custom((name) => {
            return name.match(/^[A-Za-z ]+$/) && name.length > 1;
        })
        .withMessage('First name must be at least 2 letters and contain only letters.'),
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29