Hello Jay

Hello Jay

1572060495

Express Validator Tutorial with Input Validation in Node.js

Today we are going to learn how to use Express Validator in a Node.js app to implement server-side validation to validate user data.

In this post, we will understand how to use express-validator module to make the input validation from the server side. We will build a basic Node/Express app with the help of a couple of npm packages such as express-session, express-validator, cookie-parser, etc.

Why Server-side Validation?

Well, if you consider Man in middle attacks. Security is the most significant expect when it comes to safety and security; a server must not have total faith on the client-side. The client-side validation can be deciphered, or data can be manipulated by just turning off the JavaScript in the browser.

Validation has a significant role in web or mobile application security. No matter whether you build your app using the Express framework or any other Node.js framework.

In this tutorial, we will look at how to validate form data in an Express/Node.js app using a popular open-source npm package called express-validator.

Why express-validator is useful?

As per their official documentation:
express-validator is a set of express.js middlewares that wraps validator.js validator and sanitizer functions.

  • Check API
  • Filter API
  • Schema Validation
  • Validation chain API
  • Validation Result API
  • Custom Error Messages
  • Sanitization chain API
  • Validation middlewares

To know more about express-validator module refer to their official documentation.

Input Validation with Express Validator Example

We will create an Express API to make the POST request to the server. If the request gets failed, then we will display the form validation errors for name, email, password and confirm password input fields.

We will install Bootstrap 4 to build the basic form and to display the HTML partials we will use up express-hbs module in our Express/Node app.

Set Up Express/Node Form Validation Project

Create express input validation project folder for by running the below command.

mkdir express-node-form-validation

Get inside the project directory.

cd express-node-form-validation

Run command to create package.json:

npm init

Next, install nodemon module with --save-dev attribute for development purpose. This module takes care the server restarting process.

npm install nodemon --save-dev

Install Express Validator Package

Next, install following module from npm to build express and node app.

npm install body-parser cookie-parser cors express-session --save

In order to implement input validation we need to install express and express-validator modules.

npm install express express-validator --save

Configure Node/Express Server

Create app.js file, here in this file we will keep node server settings. Then, go to package.json file and add start: “nodemon app.js” property inside the scripts object and also define main: "app.js" property.

Here is the final package.json file.

// package.json

{
  "name": "express-node-server-side-form-validation",
  "version": "1.0.0",
  "description": "Express and Node.js server-side form validation tutorial with examples",
  "main": "app.js",
  "scripts": {
    "start": "nodemon app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Digamber",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cookie-parser": "^1.4.4",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-hbs": "^2.1.2",
    "express-session": "^1.17.0",
    "express-validator": "^6.2.0"
  },
  "devDependencies": {
    "nodemon": "^1.19.4"
  }
}

Next, go to app.js file and include the following code in it.

// app.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const session = require('express-session');

// Express settings
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cors());

app.use(cookieParser());
app.use(session({
    secret: 'positronx',
    saveUninitialized: false,
    resave: false
}));

// Define PORT
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
    console.log('Connected to port ' + port)
})

Set Up Express Handlebars View Engine

Now, we need to install express-hbs module, It’s a handlbars templating view engine. Run below command to install the module.

npm install express-hbs --save

Next, create views folder inside the express input validation project folder. And, also create partials folder within the views folder, following will be the folder architecture views > partials.

Then, create public folder inside the express validation folder. Also, create css and js folder inside the public folder.

Next, Download Bootstrap and take bootstrap.min.css and bootstrap.min.js files and put inside their respective folders inside the public folder.

Express validator tutorial

Create user.hbs file using Bootstrap inside views/partials/ folder, add the following code.

<!-- user.hbs -->

<html lang="en">

<head>
    <title>Express Node Form Validation</title>
    <link href="../../public/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="../../public/css/styles.css" rel="stylesheet" type="text/css">
</head>

<body>
    <nav class="navbar navbar-dark bg-primary">
        <a class="navbar-brand" href="#">Express Form Data Validation</a>
    </nav>

    <div class="container">
        <div class="col-md-12">
            <form method="post" action="">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" name="name" />
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="text" class="form-control" name="email" />
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" class="form-control" name="password" />
                </div>
                <div class="form-group">
                    <label>Confirm Password</label>
                    <input type="password" class="form-control" name="confirm_password" />
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-danger btn-block">Create</button>
                </div>
            </form>
        </div>
    </div>
</body>

</html>

Next, add express handlebars view engine settings in app.js file.

// app.js

const hbs = require('express-hbs');

// Serve static resources
app.use('/public', express.static('public'));

// Render View
app.engine('hbs', hbs.express4({
    partialsDir: __dirname + '/views/partials'
}));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views/partials');

Run following command and check the user form in the browser on this url http://localhost:4000/user.

npm start

express input validation form

Implement Input Validation in Express Routes

Now, create express routers to make the POST and GET requests using Express.js. Create routes folder and create user.routes.js file inside of it and paste the given below code.

// routes/user.routes.js

const express = require("express");
const session = require('express-session');
const router = express.Router();

const { check, validationResult } = require('express-validator');

router.post('/create-user',
    [
        check('name')
            .not()
            .isEmpty()
            .withMessage('Name is required'),
        check('email', 'Email is required')
            .isEmail(),
        check('password', 'Password is requried')
            .isLength({ min: 1 })
            .custom((val, { req, loc, path }) => {
                if (val !== req.body.confirm_password) {
                    throw new Error("Passwords don't match");
                } else {
                    return value;
                }
            }),
    ], (req, res) => {
        var errors = validationResult(req).array();
        if (errors) {
            req.session.errors = errors;
            req.session.success = false;
            res.redirect('/user');
        } else {
            req.session.success = true;
            res.redirect('/user');
        }
    });

router.get('/', function (req, res) {
    res.render('user', {
        success: req.session.success,
        errors: req.session.errors
    });
    req.session.errors = null;
});

module.exports = router;
  • Import check, validationResult class from the express-validator module in the user.routes.js file.
  • Add input validation with HTTP POST request declare the errors array as a second argument in the router.post() method.
  • We declared the express validators check() method and passed the input validation name in it, and used the .not(), .isEmpty() methods in it. To display the error message we used the .withMessage() method.
  • The .isEmail() does the email validation in the Express API.
  • To make the password required and confirm password validation, we declare the custom method.

Next, go to app.js and add the express user router.

// app.js

// User router
const user = require('./routes/user.routes');

// Initiate API
app.use('/user', user)

Show Server-Side Validation Errors in Node App

To show the validation errors in the handlebar view template. Go, to views/partials/user.hbs file and add the following code in it.

<!-- user.hbs -->

<html lang="en">

<head>
    <title>Express Node Form Validation</title>
    <link href="../../public/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="../../public/css/styles.css" rel="stylesheet" type="text/css">
</head>

<body>
    <nav class="navbar navbar-dark bg-primary">
        <a class="navbar-brand" href="#">Express Form Data Validation</a>
    </nav>

    <div class="container">
        <div class="col-md-12">
            {{# if errors }}
              {{# each errors }}
                <p class="alert alert-danger">{{ this.msg }}</p>
              {{/each}}
            {{/if}}

            <form method="post" action="/user/create-user">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" class="form-control" name="name" />
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="text" class="form-control" name="email" />
                </div>
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" class="form-control" name="password" />
                </div>
                <div class="form-group">
                    <label>Confirm Password</label>
                    <input type="password" class="form-control" name="confirm_password" />
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-danger btn-block">Create</button>
                </div>
            </form>
        </div>
    </div>
</body>

</html>

Express Server-Side Validation Errors

Conclusion

Finally, we have completed Express Validator Tutorial with Input Validation in Node.js. Such as name, email, password and confirm password, share with others if you liked this tutorial. Thank you !

#node.js #express #npm #api #wevdev

What is GEEK

Buddha Community

Express Validator Tutorial with Input Validation in Node.js

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers

Aria Barnes

Aria Barnes

1622719015

Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.

 

Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development

Node.js Express EJS Layouts and Partials Tutorial

Today we are going to look at how we can use Express EJS Layouts to help us with website templating which ultimately help us to avoid writing duplicated code as well as making our website/application easily maintainable.

I had to cut off the intro as the music was too lound.

SOURCE FILES
https://raddy.co.uk/blog/nodejs-express-layouts-and-partials/

CONNECT with RaddyTheBrand
Website: https://www.raddy.co.uk
GitHub: https://www.github.com/RaddyTheBrand
Instagram: https://www.instagram.com/RaddyTheBrand
Twitter: https://www.twitter.com/RaddyTheBrand
Newsletter: https://www.raddy.co.uk/newsletter

DONATE to RaddyTheBrand
BuyMeACoffee: https://www.buymeacoffee.com/RaddyTheBrand
PayPal: https://bit.ly/3tAuElv

#partials #ejs #node.js #node #express #node.js express ejs layouts and partials tutorial

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application

Node JS Server Side Form Validation using Express-Validator, Body-Parser and EJS

Today we are going to do some server-side form validation using the Express-validator, Body-parser and for the view engine, I will be using EJS.

This is an introduction video, but it should give you enough knowledge to get you started with form validation.

As you might already know it’s usually good practice to validate user input on Server Side because you can protect against malicious users, who can easily bypass your client-side scripting language and submit dangerous input to the server.

BLOG POST & SOURCE FILES
https://raddy.co.uk/blog/node-js-form-validation-using-express-validator-and-ejs/

Introduction: (0:00)
Project Overview: (1:00)
Views & Form: (3:20)
Form Validation: (9:34)
Outro: (20:37)

CONNECT with RaddyTheBrand
Website: https://www.raddy.co.uk
GitHub: https://www.github.com/RaddyTheBrand
Instagram: https://www.instagram.com/RaddyTheBrand
Twitter: https://www.twitter.com/RaddyTheBrand
Newsletter: https://www.raddy.co.uk/newsletter

DONATE to RaddyTheBrand
BuyMeACoffee: https://www.buymeacoffee.com/RaddyTheBrand
PayPal: https://bit.ly/3tAuElv

#ejs #node js #node #express-validator #body-parser #node js server side