Express JS Validate form data using express-validator

Express JS Validate form data using express-validator

validate form data in Express JS using express-validator

Hi, in this tutorial you will learn how to validate form data in Express JS using the express-validator module.


Express Validator:

express-validator is a set of express.js middlewares that wraps validator.js validator and sanitizer functions.


So first, install the express-validator module by running the npm install express-validator --save command.

After installing that import that module in you application –

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

The body() is used to validate form fields and that is used as a middleware –

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

Through the validationResult you will get the result of the validation –

app.post('/', 
[
  // check it is a valid email address
  body('email').isEmail(),
  // check it is a number
  body('phone_number').isNumeric(),
],
(req, res) => {
  const validation_result = validationResult(req);
}
);

The validationResult function returns an object, and in the object, there are five functions –

  • isEmpty()
  • array()
  • mapped()
  • formatWith()
  • throw()

To validate the data of a form we only need two functions –isEmpty() and array() function

The isEmpty() function return a Boolean value true or false.

If the Validation fails, it will return false otherwise it will return true.

app.post('/', 
[
  body('email').isEmail(),
  body('phone_number').isNumeric(),
],
(req, res) => {
  const validation_result = validationResult(req);
  if(validation_result.isEmpty() === true){
    //User has filled in all the form fields correctly
  }
  else{
    //User has entered some invalid input values
  }
}
);

But how can you know which input fields are filled in incorrectly by a user, for that we will use the array() function.

The array() function returns an array of objects or an object or it will return an empty array.

It depends on how many fields are filled in incorrectly.

An object that returns by the array(), it contains the four Properties –

{ 
  location: 'body',
  param: 'email',
  value: '',
  msg: 'Invalid value' 
}

How to set custom message (msg)

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

After that, you will get this –

{ 
  location: 'body',
  param: 'email',
  value: '',
  msg: 'Invalid email address'
}

Full Code

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

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

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

app.post('/', 
[
  body('email','Invalid Email Address').isEmail(),
  body('number','Invalid Number').isNumeric(),
],
(req, res) => {
  const validation_result = validationResult(req);
  
  if(validation_result.isEmpty() === true){
    //User has filled in all the form fields correctly
    res.send('All is ok');
  }
  else{
    let sendError = '';

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

    res.send(sendError);
  }
}
);

app.listen(3000);

How to apply multiple validations in one field –

body('number','Invalid Number or Number must be between 5 and 10 characters').isNumeric().isLength({min:5,max:10}),

How to make a custom validator –

In the below example we are checking that the E-mail already in use or not

app.post('/', body('email').custom(value => {
  return User.findUserByEmail(value).then(user => {
    if (user) {
      return Promise.reject('E-mail already in use');
    }
  });
}), (req, res) => {
  // Handle the request
});

Important resources


Previous is – Express JS File Upload

Posts Navigation


Leave a Reply

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