Powerful Data Validation with Yup in Node.js

  • Fri May 26 2023
  • Jazim Abbas

If you would like to follow along with the code example that I am using, you can find the source code on the GitHub repository created by me.

In Node.js, there are multiple ways to add validation to your applications. You can simply use if-else conditions to validate inputs, utilize existing validation packages, or even publish your own custom validation package tailored to your specific needs. However, manual validation in larger projects can become a repetitive task. Additionally, when adding complex validations where certain fields should only be validated under specific conditions, a more advanced approach is required. In this article, we will explore how we can validate Node.js apps, specifically Express.js apps, using the powerful "Yup" package.

Note: In this article, we will focus on exploring common validation rules that are frequently used in applications. By the end, you'll have a solid understanding of how to leverage the Yup package to streamline validation in your Node.js applications.

Understanding Validation Scope

The fields you choose to validate depend entirely on the requirements of your application. Generally, I tend to validate request bodies, request parameters, request queries, and environment variables. However, with Yup, you can validate any data you want, making it a versatile tool for your validation needs.

Exploring the Power of Yup

Yup is an incredibly powerful package that allows you to validate various data types, including arrays and objects. You can define custom validation rules and even implement conditional validations, where certain fields are validated only when specific conditions are met. For example, imagine you're building a profile update feature that includes an option to reset the password. In this case, you would have fields like "username," "password," and "confirm password." To ensure meaningful validation, you would want to validate the "confirm password" field only when the "password" field is provided.

Yup not only handles validation but also allows you to transform values after validation. This feature can be useful when you need to manipulate data based on the validation results.

Validate Request Body

Let's consider an example where your app has an endpoint, /register, which is responsible for creating user accounts. Instead of directly saving user input into the database, it's essential to validate the data to ensure its correctness. For instance, you may require that the "name" field has a minimum of 6 characters and that the "password" field contains a minimum of 8 characters, including at least one uppercase letter. Achieving this using if-else conditions is possible, but the Yup package simplifies the process by allowing you to apply validation rules effortlessly. Yup takes care of the rest once you've defined the validation rules.

const yup = require("yup");

const authSchema = yup.object({
  body: yup.object({
    name: yup.string().min(8).max(40).required().label("Name"),
    email: yup.string().email().required().label("Email"),
    password: yup
      .string()
      .required()
      .min(8)
      .max(50)
      .matches(
        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()\-_=+{};:,<.>])(?!.*\s).{8,}$/,
        "Password must contain at least one lowercase letter, one uppercase letter, one digit, and one special character"
      )
      .label("Password"),
  }),
});

In the provided code snippet, you can observe how easy it is to add validation rules using Yup. Suppose you want to customize the validation message for each rule; that can also be accomplished effortlessly. For example:

name: yup.string("Name must be string").required("Name is a required field")

By adding the validation message within the curly braces, you can assign custom error messages to any validation rule.

In the code snippet, you can see that I added a key called "body" and defined the validation rules. This allows us to validate the entire request, not just the request body. We can apply validation rules to request parameters, query parameters, and request bodies using this approach.

Yup provides a convenient and flexible way to validate request data, ensuring that it meets the required criteria before further processing.

Validate Yup Schema

In every Yup schema, there is a helpful function called "validate" that is used to perform the actual validation. This function returns a promise and throws an error if any validation fails. When calling this function, we can provide a second argument called "abortEarly," which determines the behavior of the validation process. If "abortEarly" is set to true, the function throws an error as soon as the first validation failure occurs, without waiting for all validations to run. On the other hand, if we set "abortEarly" to false, the function continues running all validations and collects all the error messages.

const Errors = require("./custom-errors");

module.exports = async function (schema, fields, abortEarly = false) {
  try {
    return schema.validate(fields, { abortEarly });
  } catch (ex) {
    throw new Errors.ValidationError({
      message: "Please enter valid information",
      errors: ex.errors,
    });
  }
};

The code snippet above shows a helper function designed to validate any Yup schema. It uses a custom class called "ValidationError," which extends the native Error class in Node.js. This function takes a Yup schema as its first argument and then calls the "validate" function of that schema to perform the validation.

In case of any validation errors, the function catches the exception and throws a custom "ValidationError" error. The error object includes a generic message, such as "Please enter valid information," and an "errors" property that contains an array of specific error messages generated by Yup during the validation process.

By using this helper function, you can easily validate data against any Yup schema and handle validation errors in a consistent and customizable manner.

Validation Middleware

The provided code snippet showcases a validation middleware that utilizes the validate helper function we discussed earlier. This middleware is responsible for validating a schema and ensuring that the request data meets the specified criteria. If the validation is successful, the middleware proceeds by calling the next middleware in the chain.

const validate = require("../libs/validate");

module.exports =
  (schema, abortEarly = false) =>
  async (req, _, next) => {
    await validate(schema, { body: req.body, params: req.params, query: req.query }, abortEarly);

    next();
  };

As you can observe, this middleware not only validates the request body but also the request parameters (req.params) and query parameters (req.query). By passing these different parts of the request to the validate function, you can ensure comprehensive validation of the entire request.

The validate function, which we discussed earlier, is an abstraction that encapsulates the logic for validating a Yup schema. It allows you to validate not only request data but also other entities, such as environment variables, as per your specific requirements.

By employing this validation middleware in your Express.js application, you can streamline the validation process and ensure that incoming data adheres to the defined schema before further processing takes place.

Where to Call the Validation Middleware

In the provided code snippet, the validation middleware is being called before processing the request body. By placing the validation middleware as a parameter in the route handler, you ensure that the request body is validated before proceeding with the route logic.

const router = require("express").Router();
const validate = require("./middlewares/validate");
const { authSchema } = require("./libs/validations/auth");

router.post("/", validate(authSchema), (req, res) => {
  res.json(req.body);
});

module.exports = router;

In this example, the validate middleware function, which we defined earlier, is applied to the route using router.post. By passing authSchema (the Yup schema for authentication) as an argument to the validate middleware, you initiate the validation process. This ensures that the request body complies with the specified schema before proceeding to the route handler function.

After successful validation, the route handler function is executed, and in this case, the response is a JSON representation of the request body (req.body).

By placing the validation middleware in this position, you can guarantee that the request body has been validated prior to any further processing, maintaining data integrity and adhering to the defined schema.

Validate Request Query Parameters

In scenarios where you are accepting query parameters in your API endpoints, it is crucial to validate those parameters before utilizing them. This validation helps protect against potential SQL injection attacks and ensures that the provided query parameters adhere to the expected criteria.

You can use the Yup package to define a schema specifically for validating query parameters. Here is an example:

const yup = require("yup");

const collectionSchema = yup.object({
  query: yup.object({
    sort: yup.string().oneOf(["asc", "desc"]).required().label("Sort"),
    limit: yup.number().min(5).max(50).required().label("Limit"),
    pageSize: yup.number().min(1).required().label("Page Size"),
  }),
});

module.exports = { collectionSchema };

In the above code snippet, we define a Yup schema called collectionSchema that represents the expected structure and validation rules for the query parameters. The schema includes validation rules for parameters like "sort," "limit," and "pageSize."

To use this schema, you can incorporate it into a validation middleware function similar to what we previously discussed for request body validation. By passing the collectionSchema to the middleware, you can automatically validate the provided query parameters and ensure they meet the specified criteria.

Validating query parameters helps prevent potential security vulnerabilities and ensures that the parameters are within the expected range or values. By integrating this validation process into your middleware, you can enhance the overall security and reliability of your API endpoints.

Validate Request Parameters

When working with API endpoints that include request parameters, it is essential to validate those parameters to ensure their correctness and adherence to specific criteria. For example, when you have an endpoint like /item/:id, where id should be a valid MongoDB ID, you can use Yup validation to verify the parameter's validity before processing it further.

Here is an example of validating request parameters using Yup:

const yup = require("yup");
const mongoose = require("mongoose");

const itemSchema = yup.object({
  params: yup.object({
    id: yup.string().test({
      name: "valid-mongodb-id",
      message: "Invalid item ID",
      test: (value) => {
        return mongoose.Types.ObjectId.isValid(value);
      },
    }),
  }),
});

module.exports = { itemSchema };

In the provided code snippet, we define a Yup schema called itemSchema that specifically validates the request parameters. Within the schema, we specify a validation rule for the parameter id. The test function allows us to perform a custom validation check using a callback function. In this case, we verify whether the provided id is a valid MongoDB ID using the mongoose.Types.ObjectId.isValid() method.

If the validation test fails, Yup will generate an error message indicating that the item ID is invalid. This validation helps prevent any exceptions or errors that might occur when using an incorrect or invalid MongoDB ID in your application.

By using the itemSchema in your validation middleware or directly in your route handler, you can ensure that the request parameters are validated according to the defined criteria, promoting data integrity and preventing potential issues caused by invalid parameter values.

Validate Environment Variables

Validating environment variables during the application startup is indeed a good practice. It helps ensure that the required environment variables are provided and have the expected values, preventing potential issues or errors due to missing or incorrect configuration.

Here is an example of using Yup to validate environment variables:

const yup = require("yup");

const envVarSchema = yup.object().shape({
  DB_USER: yup.string().required().label("DB User"),
  DB_HOST: yup.string().required().label("DB Host"),
  DB_PORT: yup.number().required().label("DB Port"),
});

module.exports = { envVarSchema };

In the code snippet above, we define a Yup schema called envVarSchema specifically designed for validating environment variables. The schema specifies validation rules for the DB_USER, DB_HOST, and DB_PORT variables. For example, we require that the DB_USER and DB_HOST variables are strings and that the DB_PORT variable is a number.

By incorporating this schema into your bootstrap process, as shown in the previous example, you can ensure that all the required environment variables are present and meet the specified validation criteria before your application starts. If any of the variables are missing or do not satisfy the validation rules, an error will be thrown, and you will be alerted to the configuration issue.

This approach helps catch configuration errors early, reducing the need for manual debugging and providing a smoother deployment and runtime experience for your application.

App Bootstrap

The provided code snippet demonstrates the bootstrap process for your application. It incorporates the validate function we discussed earlier, as well as a Yup schema specifically designed for validating environment variables.

const app = require("./app");
const validate = require("./libs/validate");
const { envVarSchema } = require("./libs/validations/env-vars");

async function bootstrap() {
  try {
    await validate(envVarSchema, process.env);

    const PORT = process.env.PORT || 8000;
    app.listen(PORT, () => console.log(`App is listening on port ${PORT} ...`));
  } catch (err) {
    console.log("Error while bootstraping app", err);
  }
}

bootstrap();

In this example, the bootstrap function serves as the entry point for your application. Here's a breakdown of the process:

  • In this example, the bootstrap function serves as the entry point for your application. Here's a breakdown of the process:
  • If the environment variables pass the validation successfully, the code proceeds to the next step. Otherwise, if any validation errors occur, an error is thrown and caught in the catch block.
  • The PORT variable is assigned a value from the environment variable process.env.PORT if it exists, or a default value of 8000 if it is not defined.
  • Finally, the Express.js application is started by calling app.listen() on the specified port. A log message is displayed to indicate that the application has started successfully.
  • If any error occurs during the bootstrap process, it is caught in the catch block, and an error message is logged.

Conclusion

In conclusion, the Yup validation package offers a powerful and efficient solution for validating data in Node.js applications. By leveraging Yup's capabilities, you can easily define validation rules, handle complex scenarios, and ensure data integrity across request bodies, query parameters, and more. Whether it's validating user input, environment variables, or request parameters, Yup simplifies the process and enhances the reliability of your application. By incorporating Yup into your validation workflow, you can streamline development, improve security, and deliver a more robust and error-free application.