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'));