Introduction

In web-based systems, we frequently work with forms in real-world applications.

We might already have frontend validation for form but as a rule of thumb as a web developer, we also need to ensure all the form inputs are validated via the backend.

One simple user mistake (unsupported user input) away to break your whole application. In the worst cases, some malicious code might be thrown at any moment to break the apps by hackers.

So we need to cover all these possible threats on both the frontend and backend.

On that note In this post, we going to walk through how to implement backend validations in express js.  

Implementation

In this post, we going to use the express-validator library to handle the backend validations. It wraps the validator.js functionalities for express js. (validator js is a vanilla javascript package to handle the validations).

By using the Express Validator, we can simply add the validation middleware to our app. We can use its built-in validation rules, as well as write new validation rules based on our requirements.

Install the express-validator via npm

npm install express-validator

 

Adding a validator

We need to import first in order to use the express validator within our app.


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

  In this code block, we are going to create a simple user sign-up route function.

app.post('/user', [
  body('name')
    .isLength({ min: 3 }) // value is at least 3 characters
    .trim() // leading or trailing whitespace
    .withMessage('Name must be at least 3 characters'), // specifies the error message
  body('email')
    .isEmail() // check the value is a valid email address
    .normalizeEmail() // transforming value into a standardized format
    .withMessage('Invalid email')
  // Add more validation rules for other fields if needed
], (req, res) => {

  const errors = validationResult(req);

  if (!errors.isEmpty()) { // If there are errors, return Bad Request response status
    return res.status(400).json({ errors: errors.array() }); // Return errors as JSON array
  }

  // If validation passes, handle the request
  const { name, email, password } = req.body;

  // Perform further actions with the validated data
  // For example, you might save the user to a database
  // or perform some other business logic

  // Send a success response
  return res.status(200).json({ message: 'User created successfully', data: { name, email } });
});


  Following are some of the other frequently used inbuild validation methods in the express-validator npm package.

  • isNumeric(): to check the inputs contain numeric values only.
  • escape(): to eliminate HTML string values.
  • toInt(): to convert an input value to a number.
  • toLowerCase(): to convert an input to lowercase.

 

Custom validation

We can write our own validation rules and combine them with an express validation package.

//function to check whether or not the input contains an Uppercase letter
const containsUppercase = (value) => {
  return /[A-Z]/.test(value);
};

app.post('/user', [
  body('password')
		.custom(containsUppercase).withMessage('Password must contain at least one uppercase letter'),
],
(req, res) => {
  //rest of the code is the same as the above block
});

You can check the official express-validator documentation for more details.

 

Conclusion

In this blog post, we went through how to get started with the express validator using our own validation rules as well as inbuild validation functions.

Happy learning/coding 😎