In the process of constructing a contact form and incorporating express-validator for validation, I am currently focused on error handling. Below is a snippet of the code from my app.js file that pertains to this matter:
// CREATE (POST) ROUTE - add new prospect to the DB
app.post('/contact', [
check('firstName', 'Please enter at least one letter').not().isEmpty().trim().escape(),
check('lastName', 'Please enter at least one letter').not().isEmpty().trim().escape(),
check('emailAddress', 'Please enter a valid email address').isEmail().normalizeEmail(),
check('message', 'Please enter at least one letter').not().isEmpty().trim().escape()
], (req, res) => {
// GET AND SANITIZE DATA
var firstname = req.sanitize(req.body.firstName);
var lastname = req.sanitize(req.body.lastName);
var emailaddress = req.sanitize(req.body.emailAddress);
var message = req.sanitize(req.body.message);
var newProspect = { firstName: firstname, lastName: lastname, emailAddress: emailaddress, phoneNumber: phonenumber, message: message };
// HANDLE FORM VALIDATION ERRORS
const errors = validationResult(req);
if(!errors.isEmpty()) {
console.log(errors.array());
return res.status(422).render('contact-form', {
errorMessage: errors.array()[0].msg
});
}
For displaying errors on the browser, I have added the following code snippet in my contact-form.ejs file right above the form section:
<% if(errorMessage) { %>
<div class="user-message user-message--error"><%= errorMessage %></div>
<% } %>
Upon loading the contact-form route, the following error is encountered:
ReferenceError: /home/ubuntu/workspace/views/contact-form.ejs:13
11|<p class="lead">Fill out the form below and we will respond as soon as possible.
12|</p>
>> 13|<% if(errorMessage) { %>
14|<div class="user-message user-message--error"><%= errorMessage %></div>
15|<% } %>
16|<div class="form">
errorMessage is not defined
It seems like I am overlooking a crucial detail here, but due to my limited experience, I am struggling to pinpoint the exact issue.
Perhaps, the better query is how to effectively utilize the 'errorMessage' variable from my app.js in the contact-form.ejs template to prevent the occurrence of the 'undefined' error?