Node JS Form Handling: GET, POST Requests, Form Data Validation

Node JS
Node JS Form Handling: GET, POST Requests, Form Data Validation

In this Node JS Form Handling tutorial, you will learn how to get Form data through the GET and POST requests, and how to validate the form data (Form Validation).

Content of Form Handling in Node.js

✍ Before getting started

In this tutorial, we will use Express.js framework. So frist,  create a new folder on your desktop called node-form-handling, the name is completely up to you, basically, this is our app folder.

After that, go inside the app folder and initialize the npm, and then you have to install the express.js (use the following the command to install it)–

npm i express

GET Request in Node JS

You can access GET requested data using – req.query

const express = require('express');
const app = express();

app.get('/', (req, res) => {
    // HTML Form
    res.send(`<form action="/test" method="GET">
    <label>Username</label><br>
    <input type="text" name="username" placeholder="Enter Username"><br>
    <label>Password</label><br>
    <input type="password" name="pass" placeholder="Enter Password"><br><br>
    <input type="submit">
</form>`);
});

app.get('/test', (req,res) => {
    //Displaying the GET data in console
    console.log(req.query);
    res.send('Check the console');
});

app.listen(3000, () => console.log('Your app listening on port 3000'));

Parse URL params value in Node JS

You can parse the URL params data using – req.params

const express = require('express');
const app = express();

app.get('/test/:id', (req,res) => {
    console.log(`The ID is - ${req.params.id}`);
    res.send('Check the console');
});

app.listen(3000, () => console.log('Your app listening on port 3000'));
http://localhost:3000/test/21
The ID is - 21

POST Request in Node JS

If you want to get the data requested from the POST method, you have to use the express.urlencoded() middleware.

After applying the middleware, now you can access the post data using req.body

const express = require('express');
const app = express();

// Applying the middleware
app.use(express.urlencoded({extended:false}));

app.get('/', (req, res) => {
    // HTML Form (POST Method)
    res.send(`<form action="/test" method="POST">
    <label>Username</label><br>
    <input type="text" name="username" placeholder="Enter Username"><br>
    <label>Password</label><br>
    <input type="password" name="pass" placeholder="Enter Password"><br><br>
    <input type="submit">
</form>`);
});

app.post('/test', (req,res) => {
    console.log(req.body);
    res.send('Check the console');
});

app.listen(3000, () => console.log('Your app listening on port 3000'));

JSON payload in Node JS

But, if you want to request the data through the REST API with JSON payload, then you have to apply the express.json() middleware.

const express = require('express');
const app = express();

app.use(express.json());

app.post('/test', (req,res) => {
    res.json({
        "data_from_server":{
            ...req.body
        }
    });
});

app.listen(3000, () => console.log('Your app listening on port 3000'));

Form Validation in Node JS

In this tutorial, we will use the express-validator package to validate the form data. This package is a set of express.js middlewares that wraps validator.js validator and sanitizer functions.

Installation of express-validator

npm i express-validator

Use of express-validator

After installing that, import the body, validationResult from that package.

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

The body() is used as a middleware to validate the form fields. This method takes the name of the input field.

isEmail() it is an inbuilt method to validate an email address, and in the validator.js, there are lots of inbuilt methods to validate other types of fields.

app.post('/test',

//<input type="text" name="user_email">
body('user_email').isEmail(),

(req,res) => {

    const validation_result = validationResult(req);

});

The validationResult method returns the validation results, basically, it returns the five methods. But, we only need two methods to validate the form data – isEmpty() and array()

  1. isEmpty()
  2. array()
  3. mapped()
  4. formatWith()
  5. throw()

The isEmpty() method returns FALSE, if the validation fails, else it will return TRUE.

app.post('/test',

//<input type="text" name="user_email">
body('user_email').isEmail(),

(req,res) => {

    const validation_result = validationResult(req);

    if(validation_result.isEmpty()){
        res.send('All is ok');
    }
    else{
        //User has entered some invalid input values
        console.log(validation_result.array());
    }

});

The array() method returns an array of objects, which includes all the fields that are incorrectly filled in by a user.

[
  {
    value: 'test',
    msg: 'Invalid value',
    param: 'user_email',
    location: 'body'
  }
]

Array of body() middlewares

You can add multiple body middlewares in an array for validating multiple input fields.

app.post('/test',

/* <form>
    <input type="text" name="user_email">
    <input type="text" name="number">
</form> */
[
    body('user_email').isEmail(),
    body('number').isNumeric()
],

(req,res) => {

    const validation_result = validationResult(req);

});

Set custom error message (msg)

The second parameter of the body() method is for adding custom error message.

body('user_email','Invalid email address').isEmail(),

Apply multiple validations in one field

You can implement multiple validations in a field by chaining the validation methods.

body('number').isNumeric().isLength({min:5,max:10}),

Full Code

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

app.use(express.urlencoded({extended:false}));

app.get('/', (req,res) => {
    res.send(`<form action="/test" method="POST">
    <label>Email</label><br>
    <input type="text" name="user_email" placeholder="Enter email"><br>
    <label>Password</label><br>
    <input type="password" name="pass" placeholder="Enter password"><br><br>
    <input type="submit">
</form>`);
});

app.post('/test',
[
    body('user_email', 'Invalid email address').isEmail(),
    body('pass', 'Password must be between 5 and 10 characters').isLength({min:5,max:10}),
],

(req,res) => {

    const validation_result = validationResult(req);

    if(validation_result.isEmpty()){

        res.send('All is ok');

    }
    else{
        let sendError = '';

        validation_result.array().forEach((error) => {
            sendError += ' <br>' + error.msg;
        });

        res.send(sendError);
    }

});

app.listen(3000, () => console.log('Your app listening on port 3000'));

Make a custom validator

This express-validator package is also allowed to create custom validators, and this makes the package more powerful and interesting.

The custom() method is used to create a custom validator. This method takes a call back function and the call back function takes a parameter to access the input field value.

app.post('/',
    body('user_email').custom((value) => {
      // This is user email.
       console.log(value);
    })
);

You can also access the request (req) inside the callback function –

app.post('/',
    body('user_email').custom((value,{req}) => {
     
        // requests
        console.log(req)
    })
);

Example of Custom Validator

The following example checks the main Password matches the confirmation-password.

If the password matches the confirm password, it will return TRUE, else it will throw the dose not match error.

app.post('/test',
[
    body('pass', 'Password must be between 5 and 10 characters').isLength({min:5,max:10}),
    body('confirmation_pass').custom((value, {req}) => {
        if (value !== req.body.pass) {
            throw new Error('Password and confirm password does not match');
        }

        return true;
    }),
],

(req,res) => {
    // Handle the request
});
const express = require('express');
const {body, validationResult} = require('express-validator');
const app = express();

app.use(express.urlencoded({extended:false}));

app.get('/', (req,res) => {
    res.send(`<form action="/test" method="POST">
    <label>Password</label><br>
    <input type="password" name="pass" placeholder="Enter password"><br>
    <label>Confirmation Password</label><br>
    <input type="password" name="confirmation_pass" placeholder="Confirmation Password"><br><br>
    <input type="submit">
</form>`);
});


app.post('/test',
[
    body('pass', 'Password must be between 5 and 10 characters').isLength({min:5,max:10}),
    body('confirmation_pass').custom((value, {req}) => {
        if (value !== req.body.pass) {
            throw new Error('Password and confirm password does not match');
        }

        return true;
    }),
],

(req,res) => {

    const validation_result = validationResult(req);

    if(validation_result.isEmpty()){

        res.send('All is ok');

    }
    else{
        let sendError = '';

        validation_result.array().forEach((error) => {
            sendError += ' <br>' + error.msg;
        });

        res.send(sendError);
    }

});

app.listen(3000, () => console.log('Your app listening on port 3000'));

For more you can read the official docs of express-validator. And file uploading is also part of the Form Handling, so you can checkout this – Node JS File Upload using express-fileupload.

You May Also Like

Leave a Comment

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