Node.js Express Form Validation Example

In this tutorial, you will learn how to validate form data and submit in node js express js applications using express-validator module.

How to Validate Form Using Express-Validator in Node js Express JS

Here are steps:

Step 1: Set Up Express JS

Open your cmd or terminal window and type express --view=ejs MyApp to set up node express JS:

npm install express-generator -g
express --view=ejs MyApp

Run cd MyApp command to navigate the project directory:

cd MyApp

Step 2: Install Validator and Required Packages

Run the following commands on the cmd to install some required pacakges on the node.js express project:

 npm install
 npm install express-flash --save
 npm install express-session --save
 npm install [email protected]
 npm install method-override --save
 npm install mysql --save

Step 3: Connect Node js Express with Mysql DB

Before connecting DB to your application, you need to create database and table by using the following SQL query:

CREATE DATABASE IF NOT EXISTS `myapp` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `nodelogin`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `users` (`id`, `name`, `password`, `email`) VALUES (1, 'test', 'test', '[email protected]');
ALTER TABLE `users` ADD PRIMARY KEY (`id`);
ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;

Next, To create one folder named lib and create a new file name db.js inside lib folder. Then add the MySQL connection code into your db.js file:

 var mysql=require('mysql');
 var connection=mysql.createConnection({
   host:'localhost',
   user:'root',
   password:'your password',
   database:'myapp'
 });
connection.connect(function(error){
   if(!!error){
     console.log(error);
   }else{
     console.log('Connected!:)');
   }
 });
module.exports = connection; 

Step 4: Import Packages and Create routes in app.js

Now, open your app.js file and import installed packages into it; like following:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var session = require('express-session');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(flash());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    secret: '123456cat',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
app.listen(5000, function () {
    console.log('Node app is running on port 3000');
});
module.exports = app;

Step 5: Render form and add Validation Rules

Simply navigate routers directory and open index.js file, Then add the following routes for form render and validation in node js express:

var express = require('express');
var router = express.Router();
var connection  = require('../lib/db');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
//display registration form page
router.get('/register', function(req, res, next){
    res.render('form', {
        title: 'Registration Page',
        name: '',
        email: '',
        password: ''
    })
})
// validate and save registration
router.post('/post-register', function(req, res, next){
    req.assert('name', 'Name is required').notEmpty()           //Validate name
    req.assert('password', 'Password is required').notEmpty()   //Validate password
    req.assert('email', 'A valid email is required').isEmail()  //Validate email

    var errors = req.validationErrors()

    if( !errors )
    {   //No errors were found.  Passed Validation!


        var user = {
            name: req.sanitize('name').escape().trim(),
            email: req.sanitize('email').escape().trim(),
            password: req.sanitize('password').escape().trim()
        }

            connection.query('INSERT INTO users SET ?', user, function(err, result) {
                //if(err) throw err
                if (err) {
                    req.flash('error', err)

                    res.render('form', {
                        title: 'Registration Page',
                        name: '',
                        password: '',
                        email: ''
                    })
                } else {
                    req.flash('success', 'You have successfully signup!');
                    res.redirect('/register');
                }
            })
    }
    else
    {   //Display errors to user
        var error_msg = ''
        errors.forEach(function(error) {
            error_msg += error.msg + '<br>'
        })
        req.flash('error', error_msg)
        res.redirect('/register');
    }
})
module.exports = router;

Step 6: Create Registration Form View

Navigate to your node js project root directory and create a form name form.ejs:

<!DOCTYPE html>
<html>
<head>
  <title><%= title %> - Tutsmake.com</title>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
<div class="col-md-6 offset-md-3">
      <h5 class="card-title mb-2 mt-2">Node Js Express Form Submit with Validation</h5>
  <% if (messages.error) { %>
  <p style="color:red"><%- messages.error %></p>
  <% } %>

  <% if (messages.success) { %>
      <p style="color:green"><%- messages.success %></p>
  <% } %>

  <form action="/post-register" method="post" name="form1">
    <div class="form-group">
      <label for="exampleInputEmail1">Name</label>
      <input type="name" name="name" class="form-control" id="name" aria-describedby="nameHelp" placeholder="Enter name" value="">
    </div>
    <div class="form-group">
      <label for="exampleInputEmail1">Email</label>
      <input type="email" name="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value="">
    </div>
    <div class="form-group">
      <label for="exampleInputEmail1">Password</label>
      <input type="password" name="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="*********" value="">
    </div>
    <input type="submit" class="btn btn-primary" value="Submit">
  </form>
  </div>
</body>
</html>

Step 7: Test Application

Run the following command to start the development server:

//run the below command

npm start

Test this application using the following URL:

http://127.0.0.1:3000
OR
http://127.0.0.1:3000/register

Conclusion

That’s it; you have learned how to create and submit a form with validation in node.js express applications.

Recommended Node JS Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *