Skip to main content

Command Palette

Search for a command to run...

Sequelize Validations, Constraints

Published
View as Markdown
  1. Introduction
    Sequelize is a popular ORM (Object-Relational Mapping) for Node.js, and it supports powerful validations and constraints to ensure data integrity at both the application and database levels.
    Validations are used to check data correctness before saving to the database, and they operate at the application level.

    Constraints are database-level rules that enforce data integrity and relationships between tables.

  2. Validations in Sequelize
    Validations ensure that the data adheres to specific rules before saving it to the database. These are implemented in the model definitions and are applied at the application level. If a validation fails, Sequelize prevents the record from being inserted or updated.
    Common Validations in Sequelize:

    allowNull: false: Ensures that a field cannot be NULL.

    isEmail: true: Ensures that the field contains a valid email format.

    isNumeric: true: Ensures that the field contains only numeric characters.

    len: [min, max]: Ensures that the length of a string is between the specified minimum and maximum values.

    min & max: Used for numeric or date values to set a minimum or maximum range.

    isIn: [[values]]: Ensures that the field's value is one of the specified options.

    isUrl: true: Validates that the string is a valid URL.

    isDate: true: Ensures that the field contains a valid date.

     const User = sequelize.define('User', {
       email: {
         type: DataTypes.STRING,
         allowNull: false,
         validate: {
           isEmail: true, // Checks if it's a valid email
         },
       },
       age: {
         type: DataTypes.INTEGER,
         validate: {
           isInt: true, // Only allows integers
           min: 18,    // Minimum age must be 18
         },
       },
       username: {
         type: DataTypes.TEXT,
         allowNull: false,
         unique: true,
       },
       hashedPassword: {
         type: DataTypes.STRING(64),
         validate: {
           is: /^[0-9a-f]{64}$/i,
         },
       },
     });
    
  3. Constraints in Sequelize
    Constraints are rules applied at the database level to ensure data consistency. These constraints prevent incorrect data from being stored in the database and enforce relationships between tables.
    Common Constraints in Sequelize:

    PRIMARY KEY: Ensures that each record in the table has a unique identifier.

    UNIQUE: Ensures that a field’s value is unique across all records in the table.

    NOT NULL: Prevents NULL values from being stored in the field.

    DEFAULT: Sets a default value for a field if no value is provided.

    FOREIGN KEY: Ensures that a value in one table corresponds to a value in another table (enforces relationships).

    ON DELETE & ON UPDATE: Specifies actions to take when referenced records are deleted or updated.

     const User = sequelize.define('User', {
       id: {
         type: DataTypes.INTEGER,
         autoIncrement: true,
         primaryKey: true, // Primary key constraint
       },
       username: {
         type: DataTypes.STRING,
         unique: true, // Unique constraint, no two users can have the same username
       },
       email: {
         type: DataTypes.STRING,
         allowNull: false, // NOT NULL constraint
       },
     });
    
     const Profile = sequelize.define('Profile', {
       userId: {
         type: DataTypes.INTEGER,
         references: {
           model: User,
           key: 'id',  // Foreign key constraint, links to User table's id field
         },
         onDelete: 'CASCADE', // Deletes the profile if the user is deleted
       },
     });
    
  4. Key Differences Between Validations and Constraints

    i) Scope -

    Validations are enforced at the application level (before the data reaches the database).

    Constraints are enforced at the database level (by the database engine itself).

    ii) When to Use -

    Use validations to provide user-friendly error messages and handle errors in your application before interacting with the database.

    Use constraints to ensure the integrity of your data, even if it's not controlled by your application (e.g., data entered directly into the database).