Welcome folks today in this blog post we will be doing form
validation in node.js and express and we will be displaying custom error messages with the help of express-flash
module. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below command as shown below
npm init -y
npm i express
npm i ejs
npm i express-flash
npm i express-session
`
And after that you will see the below directory
structure of the final project as shown below
And now we need to copy paste the below code inside the index.js
file as shown beow
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
const express = require("express"); const session = require("express-session"); const flash = require("express-flash"); const bodyParser = require("body-parser"); const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()) app.use(session({ secret:"secret key", resave:false, saveUninitialized:true, cookie:{maxAge:600000} })); app.use(flash()); app.set("view engine", "ejs"); app.get("/", (req, res) => { res.render("index"); }); app.listen(3000, () => { console.log("Server listening on port 3000"); }); |
As you can see guys we are including all the packages
that we will be needing for this application. And we are including the express-session
and express-flash
middlewares And also we are setting the view engine of ejs
. And then when the user goes to the /
page we are loading the index.ejs
template.
And now we need to make the views
directory and inside it we need to make the index.ejs
file and copy paste the following code
views/index.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html> <head> <title>Example Form</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <h1 class="text-center">Form Validation</h1> <form class="text-center" method="POST" action="/"> <div class="form-inline"> <label for="email">Email</label> <input class="form-control" type="email" id="email" name="email"> </div> <div class="form-inline"> <label for="password">Password</label> <input class="form-control" type="password" id="password" name="password"> </div> <button class="btn btn-danger" type="submit">Submit</button> </form> </body> </html> |
As you can see we have included the cdn
of the bootstrap for styling the user form where we have two fields for taking the email
and the password
of the user and then we have the submit button.
And now we need to make the post
request at the /
endpoint as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
app.post("/", (req, res) => { const { email, password } = req.body; console.log(req.body) if (!email || !password) { req.flash("error", "Email and password are required"); return res.redirect('/') } else if (password.length < 8) { req.flash("error", "Password must be at least 8 characters"); return res.redirect('/') } else{ req.flash("success","Form submitted") return res.redirect('/') } }); |
As you can see guys we are taking the data
which is submitted by the user at the backend and then we are applying the validations
checking if all the fields are filled and also the length of the password is greater than 8 characters. And also if errors
takes place we are storing it inside the flash
messages using the key
value pair. And lastly we are redirecting the user to the /
endpoint. And lastly if no errors are there we are storing the success message inside the flash
and redirecting the user to the /
endpoint.
1 2 3 |
app.get("/", (req, res) => { res.render("index", { messages: req.flash() }); }); |
Now we can slightly modified the get
request where we are now passing the data
to the ejs template in the form of messages
now we need to simply display it inside the index.ejs
file as shown below
index.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<!DOCTYPE html> <html> <head> <title>Example Form</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <h1 class="text-center">Form Validation</h1> <% if (messages.error) { %> <div class="alert alert-danger text-center"> <ul> <% messages.error.forEach(function(error) { %> <li><%= error %></li> <% }); %> </ul> </div> <% } %> <% if(messages.success) {%> <div class="alert alert-success text-center"> <li><%=messages.success%></li> </div> <%} else {%> <form class="text-center" method="POST" action="/"> <div class="form-inline"> <label for="email">Email</label> <input class="form-control" type="email" id="email" name="email"> </div> <div class="form-inline"> <label for="password">Password</label> <input class="form-control" type="password" id="password" name="password"> </div> <button class="btn btn-danger" type="submit">Submit</button> </form> <%}%> </body> </html> |
As you can see we are applying some if
and else
statements to render out all the errors for this we are also using the foreach
loop to iterate over all the errors. And also displaying the success message as well if no error is there.