Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Models and Entities

Validation, Hooks and Timestamps

Validate data with Sequelize validators and class-validator, run code before and after saves with hooks and subscribers, and manage timestamps and soft deletes, with runnable stand-ins.

A model is also the place to keep data honest. This lesson covers three related tools: validation (reject bad data before the INSERT), hooks (run code around lifecycle events), and timestamps (record when rows were created, changed and soft-deleted).

Library code is read-only. The stand-ins implement the same lifecycle in plain JavaScript.

Validation in Sequelize

Sequelize validates on create, save and update, before any SQL runs. Rules sit in each attribute's validate object.

TypeScript
User.init(
  {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: { isEmail: true },
    },
    age: {
      type: DataTypes.INTEGER,
      validate: { min: 13, max: 120 },
    },
    username: {
      type: DataTypes.STRING,
      validate: {
        len: [3, 30],
        is: /^[a-z0-9_]+$/i,
        notReserved(value: string) {
          if (["admin", "root"].includes(value)) throw new Error("Reserved name");
        },
      },
    },
  },
  { sequelize }
);

try {
  await User.create({ email: "nope", age: 5, username: "ab" });
} catch (e) {
  // e.name === "SequelizeValidationError"; e.errors lists every failure
}

Built-ins include isEmail, isUrl, len, min, max, isIn, notEmpty and is. Custom validators are plain functions that throw. Remember that unique is enforced by the database, not by the validator, so two concurrent inserts are still caught only by the constraint.

Validation in TypeORM

TypeORM does not validate by itself. The usual partner is the class-validator package, which you call before saving (NestJS does it for you in request pipes).

TypeScript
import { IsEmail, Length, Min, validate } from "class-validator";

@Entity()
export class User {
  @PrimaryGeneratedColumn() id!: number;

  @Column() @IsEmail() email!: string;
  @Column() @Length(3, 30) username!: string;
  @Column() @Min(13) age!: number;
}

const user = users.create({ email: "nope", username: "ab", age: 5 });
const errors = await validate(user);
if (errors.length) throw new Error("Invalid user");
await users.save(user);

A cheap defence in both libraries: also add database constraints (NOT NULL, CHECK, UNIQUE). Validation gives friendly messages; constraints guarantee the rule even if some other program writes to the table.

Here is the validation idea as a runnable stand-in that collects every error, like Sequelize does:

Node.js Collect all validation errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Hooks (Sequelize) and subscribers (TypeORM)

Both libraries can run your code at lifecycle points: before and after create, update, remove and find.

TypeScript
// Sequelize hooks, defined on the model
User.addHook("beforeCreate", async (user) => {
  user.passwordHash = await hash(user.password);
});
User.afterUpdate((user) => audit.log("updated", user.id));
TypeScript
// TypeORM: listener methods on the entity...
@Entity()
export class User {
  @BeforeInsert()
  normalize() { this.email = this.email.toLowerCase(); }
}

// ...or a separate subscriber class
@EventSubscriber()
export class AuditSubscriber implements EntitySubscriberInterface<User> {
  listenTo() { return User; }
  afterInsert(event: InsertEvent<User>) { console.log("inserted", event.entity.id); }
}

Use hooks for small, local rules (normalize, hash, stamp). Avoid hiding business workflows in them: hooks are invisible at the call site, and bulk operations such as Model.update() skip individual hooks unless you opt in (individualHooks: true).

Node.js Lifecycle hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Timestamps and soft deletes

Sequelize adds createdAt and updatedAt automatically (timestamps: false turns that off). With paranoid: true it also manages deletedAt: destroy() sets it, and every normal finder adds WHERE deletedAt IS NULL.

TypeScript
const post = await Post.findByPk(1);
await post.destroy();                              // UPDATE ... SET deletedAt = now()
await Post.findAll();                              // excludes it
await Post.findAll({ paranoid: false });           // includes it
await post.restore();                              // clears deletedAt
await post.destroy({ force: true });               // real DELETE

TypeORM uses the special columns from TypeORM Entities and Columns:

TypeScript
@CreateDateColumn() createdAt!: Date;
@UpdateDateColumn() updatedAt!: Date;
@DeleteDateColumn() deletedAt?: Date;

await repo.softDelete(1);          // sets deletedAt
await repo.restore(1);             // clears it
await repo.find({ withDeleted: true });
await repo.delete(1);              // real DELETE

The soft-delete idea in SQL:

Node.js Soft delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Soft deletes keep history but have costs: unique constraints still count deleted rows (an email can never be reused unless you handle it), tables grow, and joins and raw SQL must remember the filter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does Sequelize run attribute validators?

    Validation runs first and throws a SequelizeValidationError listing the problems.
  2. 2. Which package is commonly used to validate TypeORM entities?

    TypeORM has no validators of its own; class-validator decorators plus validate() fill the gap.
  3. 3. What does a paranoid Sequelize model do on destroy()?

    paranoid enables soft deletion; use force: true for a real DELETE.
  4. 4. Why also add database constraints when you validate in code?

    Constraints guarantee the rule no matter who writes to the table.

Summary

  • Sequelize validates with per-attribute validate; TypeORM pairs with class-validator.
  • Back validation with NOT NULL, CHECK and UNIQUE constraints.
  • Hooks (Sequelize) and listeners or subscribers (TypeORM) run code around lifecycle events; keep them small.
  • Timestamps are automatic in Sequelize and column decorators in TypeORM.
  • Soft deletes hide rows with a deletedAt marker; remember the unique-constraint and growth costs.

Next: CRUD Operations