Onjsdev

Share


Validate Email And Password In Nodejs With Express-Validator


By onjsdev

Jun 2nd, 2023

it's essential to validate user credentials when registering a new user in your system. This validation must be done on the backend side, according to the specific requirements of your application.

In this article, we will show you how to validate an email and password in nodejs with express-validator package, which provides middlewares to easily validate email and password.

Create A Node Server With Expressjs

We'll build a straightforward server using Expressjs, featuring a route to handle registration requests from users.

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

// Parse the body
app.use(express.json());

// SignUp route
app.post("/signup", validateEmail(), validatePassword(), signup);

function validateEmail() {
  // Code here to validate email
  // It Will return a middleware
}

function validatePassword() {
  // Code here to validate password
  // It Will return middleware
}

function signup(req, res, next) {
  // Signup controller
}

const PORT = process.env.PORT || 3002;

app.listen(PORT, () => {
  console.log(`Server is running on PORT ${PORT}`);
});

Validate Email And Password With Express-Validator

Firstly, install the package express-validator using npm or yarn

npm install express-validator

Validate Email

Next, let's create the first middleware function, validateEmail, which will perform the following steps:

  • Check if it is an email
  • Check its characters length
  • Normalize the email according to the email provider (gmail, outlook)

const { body } = require("express-validator")
function validateEmail() {
// code here to validate email

  return body("email")
    .isEmail()
    .withMessage("Please Enter A Valid Email")
    .isLength({ max: 320 })
    .withMessage("Password must contain up to 320 characters")
    .normalizeEmail();
    
}

Validate Password

Validating passwords is essential as it enhances the security of the system by enforcing strong password policies and protecting user accounts from unauthorized access. Let's see what validatePassword function do in order.

  • Check if the password is empty
  • Check the password characters length
  • Check if the password contain at least an upper case letter
  • Check if the password contain at least an lower case letter
  • Check if the password contain at least a number
  • Check if the password contain space characters
  • Check if the password confirmation match password
// not() negates the result of the next validator.
function validatePassword() {
  return body("password")
    .notEmpty()
    .withMessage("Please Enter A Valid Password")
    .isLength({ min: 6 })
    .withMessage("Password must be at least 6 characters")
    .isLength({ max: 128 })
    .withMessage("Password must contain up to 128 characters")
    .matches(/[A-Z]/g)
    .withMessage("Password must contain an upper case letter")
    .matches(/[a-z]/g)
    .withMessage("Password must contain a lower case letter")
    .matches(/[0-9]/g)
    .withMessage("Password must contain a number")
    .not()
    .matches(/\s/g)
    .withMessage("Please do not use space characters")
    .custom((value, { req }) => {
      if (value !== req.body.passwordAgain) {
        throw new Error("Password confirmation does not match password");
      }
      return true;
    });
}

Sign Up Controller

After performing the credentials validation, in case of any errors, we can return the error to the user by utilizing the validationResult method, as shown below.

const { validationResult } = require("express-validator");

function signup(req, res, next) {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send("Eveything is ok");
}

Validation Response

After all is done, here is a test scenario that show how error response looks.

Validate email and password in nodejs using express validator package | An Error Response Example

Conclusion

In conclusion, this article demonstrated how to use a middleware provided by the express-validator package to validate an email and password in Nodejs application to protect both users and our server.

Thank you for reading.