Sling Academy
Home/Node.js/Sequelize.js: How to Validate Numbers and Text Length

Sequelize.js: How to Validate Numbers and Text Length

Last updated: December 29, 2023

Introduction

Sequelize is a popular promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication, and more. One of the critical aspects while working with data is ensuring the integrity and validity of data being persisted to the database. Validation is a key step in this process, and Sequelize provides a plethora of built-in validation tools that help ensure that your data is correct and that you are adhering to any business rules or constraints. In this article, we’ll explore how to use Sequelize to validate numbers and text lengths effectively within your models.

Basic Number Validation

Let’s begin with the basics of validating numbers in Sequelize. The most common numeric validations check for minimum and maximum values or whether a value is an integer.

const User = sequelize.define('user', {
  age: {
    type: Sequelize.INTEGER,
    validate: {
      min: 0,
      max: 150,
      isInt: true
    }
  }
});

This user model defines an `age` attribute which is an integer that must be between 0 and 150.

Advanced Number Validation

Going beyond simple min and max validations, Sequelize allows for custom validator functions where you can define more complex logic.

const Product = sequelize.define('product', {
  price: {
    type: Sequelize.FLOAT,
    validate: {
      isEven(value) {
        if (value % 2 !== 0) {
          throw new Error('Price must be an even number');
        }
      }
    }
  }
});

This product model includes a custom function to ensure that the price is always an even number.

Text Length Validation

For text fields, you can validate the length of the input string to match specific requirements, such as minimum or maximum length, or even an exact length.

const Tweet = sequelize.define('tweet', {
  content: {
    type: Sequelize.STRING,
    validate: {
      len: [0, 280] // Maximum Twitter message length
    }
  }
});

In this tweet model, we use the `len` validator to ensure the content of a tweet does not exceed 280 characters.

Combining Validations

Often, you’ll want to combine multiple validators for a single attribute to ensure data integrity thoroughly.

const Review = sequelize.define('review', {
  title: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true,
      len: [10, 100] // Title length constraints
    }
  },
  rating: {
    type: Sequelize.INTEGER,
    validate: {
      min: 1,
      max: 5,
      isNumeric: true
    }
  }
});

This review model requires that a title is not empty and must be between 10 and 100 characters, and the rating is a numeric value from 1 to 5.

Custom Validators and Asynchronous Validation

In some cases, you’ll want to perform validations that are not just based on the value itself but perhaps involve asynchronous operations, such as database lookups.

const User = sequelize.define('user', {
  username: {
    type: Sequelize.STRING,
    validate: {
      isUnique: function (value, next) {
        User.find({
          where: {username: value},
          attributes: ['id']
        })
        .then(function (user) {
          if (user) {
            return next('Username already in use!');
          }
          next();
        })
        .catch(function (err) {
          return next(err);
        });
      }
    }
  }
});

In this user model, we have a custom asynchronous validator that checks if the username is already in use.

Conclusion

In conclusion, Sequelize offers a robust set of tools for validating both numbers and text lengths in your data models. From simple checks like minimum and maximum values to more complex custom validations, Sequelize can help ensure the reliability and consistency of your data. By leveraging these features, developers can prevent invalid data from being stored in the database, thereby reducing errors and improving overall data quality.

Next Article: Sequelize.js: How to Auto-Hash Passwords

Previous Article: How to extend an existing model in Sequelize

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates