Error encountered on page load due to undefined variable thrown by the Express-validator validation process

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?

Answer №1


It appears that there may be a scope problem in your code. The errorMessage variable seems to be either undeclared or out of scope. It could be that it is declared inside the !errors.isEmpty control structure, making it inaccessible in the global scope. This could explain why the errorMessage variable is not defined when you try to use it later on.
Although I cannot verify this without the actual code, based on my past experiences, scope issues have often been the cause of similar problems. Hopefully, addressing the scope problem will lead you to a solution. If not, feel free to share more details so that we can take another look :). HTH -- Philippe

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Printing from a Windows computer may sometimes result in a blank page

Looking to incorporate a print button into an HTML page, I'm facing an issue. The majority of the content on the page should not be included in the printed version, so my approach involves hiding everything in print and then showing only the designate ...

Creating a dynamic website with user-friendly editing capabilities

Having a good understanding of html5 and css3, I am currently exploring ways to create a website that enables visitors to edit content in real time for all other users to see. While aware of the contenteditable attribute, I have found that it does not reta ...

Creating a loop to iterate through JSON data being received

I successfully used JSON to display data, but I am now wondering how I can print all the database entries into a div or table. JavaScript $(document).ready(function() { $.ajax({ type : 'POST', url : 'server.php', dataTyp ...

The JSON file overwrites entire objects instead of targeting individual ones

Is there a way to update just one specific object in a JSON file without affecting the rest? I've implemented a put request on the front-end using axios to send data to the back-end for processing. However, the current functionality replaces all obje ...

Prevent angular from being executed through a JavaScript function triggered by a button click

Here is a button: <button ng-click="deleteCompany(company.id)" class="btn btn-danger" onClick="return window.confirm('This will permanently delete the entity\n Are you sure you want to delete this post?'); "> <s ...

Is it possible to create a basic calculator with Vue.js by incorporating v-model and possibly v-if?

I am looking to create a Vue.Js component that includes an input field displaying the potential hours saved by a user switching to our software. How can I implement the v-if directive in this scenario? For users spending 20 - 30 hours, they would save 10 ...

What is the solution for fixing the CORS Error that arises during a URL Redirection?

I am currently working on setting up Google Authorization for my mobile app. The frontend is built using React Native, while the backend is powered by NodeJS with Express. While I have managed to successfully make API calls from my frontend using Axios, I ...

Unlocking the potential of the Bootstrap search dropdown

Currently, I am utilizing the following code to create a searchable dropdown menu. I found helpful guidance in this forum post. I am seeking advice on how to retrieve the value of the selected option. For example, if 'China' is chosen, I would l ...

Why won't applying a binding style affect the appearance of my Vue component?

const EventLevelBoard = { name: "EventLevel", data: { levelStyle: { display: "block" }, levelStyleinner: [ { display: "block" }, { display: "block" }, { display: "block&qu ...

Put dashes in the middle of each MongoDB post title

In my express app, users can create and view posts. Currently, I search for posts by their title. However, I am encountering an issue when the post title contains spaces. The search function works perfectly for titles without spaces, but it gives an error ...

Show the button only when the text is updated

Is there a way to display a button only when the quantity of items in the cart changes, similar to the eBay shopping cart feature? I was able to implement it but it's not functioning as expected. Here is the link to what I have so far. Does anyone kno ...

How to enable real-time file changes detection in sails for development

I recently embarked on a new project using Sails (built on Express and Node.js). Currently, I am initiating my server with the command: sails lift However, whenever I make changes to the codebase, I need to manually restart the server. Is there a way to ...

What is the best way to access the values associated with the keys in an array of objects?

I have an array of objects that has the following structure: import icon1 from '!!raw-loader!../../../icon1.svg'; import icon2 from '!!raw-loader!../../../icon2.svg'; import icon3 from '!!raw-loader!../../../icon3.svg'; import ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

In React, the clearInterval() function does not effectively clear intervals

Currently, I am implementing the following code: startInterval = () => { this.interval = setInterval(this.intervalFunction, 10000) } stopInterval = () => { clearInterval(this.interval) } However, a problem arises when I invoke the stopInte ...

"Exploring the synergy of NodeJS: incorporating callbacks within promises

Currently, I am in the process of logging into two different services and I am tasked with pushing both responses to an array. To achieve this, I have begun by creating a promiseResult which contains two promises for the login operations: var promiseR ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. https://i.sstatic.net/Ouot4.png https://i.sstatic.net/MMKjm.png H ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

Utilize jQuery to dynamically assign classes to list items within a unordered list based on the length of an array

HTML: <ul class="tickboxes"> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i></li> <li><i class="fa fa-check"></i>< ...

Is it possible to map through material-ui components within an array in React.js?

I've been attempting to implement material-ui and iterate over it within an array (to create ratings for items, similar to e-commerce websites). Unfortunately, the code is not functioning as expected. When I run it on my localhost server, no stars are ...