Skip to content
Active Record
Esc
↑↓navigate↵open⌘Jpreview
On this page

Validations

Check a record before it’s saved, and see why an invalid one wasn’t.

At a glance

To Write
declare a rule this.validates("email", { presence: true })
validate without saving await record.isValid()
read why a record is invalid record.errors.fullMessages(), errors.get("email")
run a rule only when creating on: "create"
run rules for a step of your own static validationContexts = ["signup"] as const, on: "signup"
validate an association’s records too this.validatesAssociated("tracks")
add an error yourself record.errors.add("base", "…"), in a validation callback
change a message message: "…", or this.errorMessages({ blank: "…" })

The Models

The examples use these Models, whose attributes come from their tables through the schema active-record schema generates. Each declares its validations in its static {} block:

import { ApplicationRecord } from "./application-record";

export class Account extends ApplicationRecord {
  static {
    this.validates("email", { presence: true, uniqueness: { caseSensitive: false } });
    this.validates("handle", { length: { minimum: 3, maximum: 30 }, format: /^[a-z0-9_]+$/ });
    this.validates("plan", { inclusion: ["free", "team", "enterprise"] });
    this.validates("seats", { numericality: { onlyInteger: true, greaterThan: 0 } });
    this.validates("website", { format: /^https:\/\//, allowNull: true });
    this.validates("companyName", {
      presence: true,
      if: (account) => account.isCompany === true,
      message: "is required for a company",
    });
  }
}
import { ApplicationRecord } from "./application-record";

export class Event extends ApplicationRecord {
  static {
    this.validates("endsAt", { comparison: { greaterThan: (event) => event.startsAt } });
  }
}
import { ApplicationRecord } from "./application-record";

export class Invoice extends ApplicationRecord {
  static {
    this.validates("currency", { inclusion: ["USD", "EUR"], strict: true }); // throws, not collects
  }
}
import { ApplicationRecord } from "./application-record";

export class Member extends ApplicationRecord {
  static override attributes = {
    emailConfirmation: { type: "string", virtual: true }, // typed a second time, never saved
  } as const;

  static validationContexts = ["signup"] as const;

  static {
    this.validates("email", { format: /@/, confirmation: true });
    this.validates("password", { presence: true, on: "create" });
    this.validates("inviteCode", { presence: true, on: "signup" });
  }
}
import { hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Track } from "./track";

export class Playlist extends ApplicationRecord {
  tracks = hasMany(Track);

  static {
    this.validatesAssociated("tracks");
  }
}
import { ApplicationRecord } from "./application-record";

export class Track extends ApplicationRecord {
  static {
    this.validates("title", { presence: true });
  }
}
import { ApplicationRecord } from "./application-record";

export class Booking extends ApplicationRecord {
  static {
    this.errorMessages({ onTheHour: "must be on the hour" });

    this.afterValidation((booking) => {
      if (booking.startsAt.getUTCMinutes() !== 0) {
        booking.errors.add("startsAt", { type: "onTheHour" });
      }
      if (booking.startsAt.getUTCDay() === 0) {
        booking.errors.add("base", "The room is closed on Sundays");
      }
    });
  }
}
import { ApplicationRecord } from "./application-record";

export class Product extends ApplicationRecord {
  static {
    this.errorMessages({
      greaterThan: "must be more than %{count}",
      attributes: {
        name: { blank: "needs a name customers will see" },
      },
    });
    this.humanAttributeNames({ priceCents: "Price" });

    this.validates("name", { presence: true, length: { minimum: 3 } });
    this.validates("priceCents", { numericality: { greaterThan: 0 } });
  }
}
import { Model } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;

  static {
    // Messages and names for every Model, in place of the built-in English:
    this.errorMessages({
      tooShort: {
        one: "needs at least 1 character",
        other: "needs at least %{count} characters",
      },
    });
    this.humanAttributeNames({ createdAt: "Added on" });
  }
}
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: 0f1c01679a71

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** accounts — last changed by 0001_create_tables.sql */
export const accounts = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  handle: { type: "string", null: false },
  plan: "string",
  seats: "integer",
  website: "string",
  isCompany: "boolean",
  companyName: "string",
} as const;

/** bookings — last changed by 0001_create_tables.sql */
export const bookings = {
  id: { type: "string", null: false, generateId: true },
  startsAt: { type: "datetime", null: false },
  endsAt: { type: "datetime", null: false },
} as const;

/** events — last changed by 0001_create_tables.sql */
export const events = {
  id: { type: "string", null: false, generateId: true },
  startsAt: { type: "datetime", null: false },
  endsAt: { type: "datetime", null: false },
} as const;

/** invoices — last changed by 0001_create_tables.sql */
export const invoices = {
  id: { type: "string", null: false, generateId: true },
  total: { type: "integer", null: false },
  currency: { type: "string", null: false },
} as const;

/** members — last changed by 0001_create_tables.sql */
export const members = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  password: "string",
  inviteCode: "string",
} as const;

/** playlists — last changed by 0001_create_tables.sql */
export const playlists = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
} as const;

/** products — last changed by 0001_create_tables.sql */
export const products = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
  priceCents: { type: "integer", null: false },
  createdAt: "datetime",
} as const;

/** tracks — last changed by 0001_create_tables.sql */
export const tracks = {
  id: { type: "string", null: false, generateId: true },
  playlistId: { type: "string", null: false },
  title: { type: "string", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    accounts: { attributes: accounts, primaryKey: "id" },
    bookings: { attributes: bookings, primaryKey: "id" },
    events: { attributes: events, primaryKey: "id" },
    invoices: { attributes: invoices, primaryKey: "id" },
    members: { attributes: members, primaryKey: "id" },
    playlists: { attributes: playlists, primaryKey: "id" },
    products: { attributes: products, primaryKey: "id" },
    tracks: { attributes: tracks, primaryKey: "id" },
  },
  models: {
    Account: "accounts",
    Booking: "bookings",
    Event: "events",
    Invoice: "invoices",
    Member: "members",
    Playlist: "playlists",
    Product: "products",
    Track: "tracks",
  },
});

declare module "../models/account" {
  interface Account extends TableAttributes<typeof accounts, (typeof Account)["attributes"]> {}
}

declare module "../models/booking" {
  interface Booking extends TableAttributes<typeof bookings, (typeof Booking)["attributes"]> {}
}

declare module "../models/event" {
  interface Event extends TableAttributes<typeof events, (typeof Event)["attributes"]> {}
}

declare module "../models/invoice" {
  interface Invoice extends TableAttributes<typeof invoices, (typeof Invoice)["attributes"]> {}
}

declare module "../models/member" {
  interface Member extends TableAttributes<typeof members, (typeof Member)["attributes"]> {}
}

declare module "../models/playlist" {
  interface Playlist extends TableAttributes<typeof playlists, (typeof Playlist)["attributes"]> {}
}

declare module "../models/product" {
  interface Product extends TableAttributes<typeof products, (typeof Product)["attributes"]> {}
}

declare module "../models/track" {
  interface Track extends TableAttributes<typeof tracks, (typeof Track)["attributes"]> {}
}
CREATE TABLE accounts (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL,
  handle TEXT NOT NULL,
  plan TEXT,
  seats INTEGER,
  website TEXT,
  is_company BOOLEAN,
  company_name TEXT
);
CREATE UNIQUE INDEX index_accounts_on_email ON accounts (email);
CREATE TABLE events (
  id TEXT PRIMARY KEY NOT NULL,
  starts_at DATETIME NOT NULL,
  ends_at DATETIME NOT NULL
);
CREATE TABLE invoices (
  id TEXT PRIMARY KEY NOT NULL,
  total INTEGER NOT NULL,
  currency TEXT NOT NULL
);
CREATE TABLE members (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL,
  password TEXT,
  invite_code TEXT
);
CREATE TABLE playlists (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL
);
CREATE TABLE tracks (
  id TEXT PRIMARY KEY NOT NULL,
  playlist_id TEXT NOT NULL REFERENCES playlists (id),
  title TEXT NOT NULL
);
CREATE TABLE bookings (
  id TEXT PRIMARY KEY NOT NULL,
  starts_at DATETIME NOT NULL,
  ends_at DATETIME NOT NULL
);
CREATE TABLE products (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL,
  created_at DATETIME
);
CREATE TABLE accounts (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL,
  handle TEXT NOT NULL,
  plan TEXT,
  seats INTEGER,
  website TEXT,
  is_company BOOLEAN,
  company_name TEXT
);
CREATE UNIQUE INDEX index_accounts_on_email ON accounts (email);
CREATE TABLE events (
  id UUID PRIMARY KEY,
  starts_at TIMESTAMPTZ NOT NULL,
  ends_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE invoices (
  id UUID PRIMARY KEY,
  total INTEGER NOT NULL,
  currency TEXT NOT NULL
);
CREATE TABLE members (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL,
  password TEXT,
  invite_code TEXT
);
CREATE TABLE playlists (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE tracks (
  id UUID PRIMARY KEY,
  playlist_id UUID NOT NULL REFERENCES playlists (id),
  title TEXT NOT NULL
);
CREATE TABLE bookings (
  id UUID PRIMARY KEY,
  starts_at TIMESTAMPTZ NOT NULL,
  ends_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE products (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  price_cents INTEGER NOT NULL,
  created_at TIMESTAMPTZ
);

Declaring validations

Declare validations in a Model’s static {} block with this.validates, as Account does, then check a record with isValid():

import { class AccountAccount } from "./models/account";

const const account: Accountaccount = class AccountAccount.
build<typeof Account>(this: typeof Account, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly handle: {
        readonly type: "string";
        readonly null: false;
    };
    readonly plan: "string";
    readonly seats: "integer";
    readonly website: "string";
    readonly isCompany: "boolean";
    readonly companyName: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Account) => void) | undefined): Account
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({
email?: string | undefinedemail: "jane@example.com", handle?: string | undefinedhandle: "jane", plan?: string | null | undefinedplan: "free", seats?: number | null | undefinedseats: 1, }); const const valid: booleanvalid = await const account: Accountaccount.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
(); // true; async, since uniqueness asks the database
  • Attribute names are typed, so a misspelled attribute is a compile error.
  • save() validates first, and resolves to false when a record is invalid.
  • isValid() is async, since uniqueness asks the database.

Available validators

Rule Options Error type
presence true blank
absence true present
length { minimum, maximum, is } tooShort, tooLong, wrongLength
format { with: /re/ }, or a regex invalid
inclusion { in: [...] }, or an array inclusion
exclusion { in: [...] }, or an array exclusion
numericality { onlyInteger, greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo }, or true notANumber, notAnInteger, greaterThan, …
comparison { greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo, equalTo, otherThan } blank, greaterThan, …
acceptance true, or { accept: [...] } accepted
confirmation true, or { caseSensitive } confirmation
uniqueness { scope: [...], caseSensitive }, or true taken

Every validation runs, in the order declared, so one attribute can collect several errors. Within one validates call, the rules run in the table’s order. Every rule also accepts these options:

  • allowNull skips the rule when the value is null. Otherwise null fails presence, format, inclusion, numericality, comparison, and acceptance, counts as length 0, and is never taken.
  • allowBlank skips the rule when the value is blank: null, or a string that’s only whitespace.
  • message replaces the default messages from that call.
  • if: (record) => boolean validates only when it returns true.
  • unless: (record) => boolean skips the rule when it returns true. With if as well, both must allow it.
  • strict throws instead of adding an error. See Raising instead of collecting errors.
  • on and exceptOn run the rule only when creating, only when updating, or in a context of your own. See Validating only when creating or updating.

The default messages are in English: “can’t be blank”, “is too short (minimum is 3 characters)”, “has already been taken”, and so on. Finding a built-in message lists them all, and Changing error messages shows how to replace them.

Validator details

  • presence fails a string that’s only whitespace. For a boolean, use inclusion: [true, false], since false is a value.
  • absence passes what presence fails: null and a string that’s only whitespace. So false fails it.
  • inclusion is added for you by an enum declared validate: true.
  • exclusion passes null unless the list holds it.
  • numericality only accepts numbers, so a numeric string such as "12" is notANumber. A decimal attribute’s text is the exception: it’s compared with each bound as a number, exactly.
  • comparison compares a number with a number, a string with a string, or a Date with a Date by its time. A decimal attribute compares as a number, with a number or a decimal’s text. A bound is a value, or a function of the record (see Comparing with another attribute). A blank value fails once, as blank. Blank means null or a string that’s only whitespace. Comparing a number with a Date, or any two different kinds, throws TypeError. Against a bound of NaN or an invalid Date, only otherThan passes.
  • acceptance is for a box that must be ticked. It passes true and "1", or the values you give in { accept: [...] }. A checkbox left unticked sends nothing, so null fails too. To let null pass, add allowNull: true. The box is usually a virtual attribute, since the table needn’t keep it.
  • confirmation compares the attribute with a virtual attribute named for it, such as emailConfirmation. See Confirming a value.
  • uniqueness leaves the record itself out when updating, and never treats null as taken, since a UNIQUE index lets several rows hold NULL. caseSensitive: false compares with the database’s lower(): on D1, SQLite’s lowercases only ASCII letters.

Confirming a value

Add confirmation: true for a value typed twice, with its second copy in a virtual attribute, as Member does with email and emailConfirmation:

import { class MemberMember } from "./models/member";

const 
const form: {
    email: string;
    emailConfirmation: string;
}
form
= { email: stringemail: "jane@example.com", emailConfirmation: stringemailConfirmation: "jane@exmaple.com" };
const
const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly password: "string";
    readonly inviteCode: "string";
}, {
    readonly emailConfirmation: {
        readonly type: "string";
        readonly virtual: true;
    };
}>>, "email" | "emailConfirmation">>
permitted
= class MemberMember.
Model.permit<typeof Member, "email" | "emailConfirmation">(this: typeof Member, input: unknown, ...names: ("email" | "emailConfirmation")[]): Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly password: "string";
    readonly inviteCode: "string";
}, {
    readonly emailConfirmation: {
        readonly type: "string";
        readonly virtual: true;
    };
}>>, "email" | "emailConfirmation">>
Only the named attributes of untrusted input (a JSON body, `FormData` or `URLSearchParams`): `User.create(User.permit(await request.json(), "email", "name"))`. Every other key is dropped, and each value is cast as assigning it would be.
permit
(
const form: {
    email: string;
    emailConfirmation: string;
}
form
, "email", "emailConfirmation");
const const member: Membermember = class MemberMember.
build<typeof Member>(this: typeof Member, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly password: "string";
    readonly inviteCode: "string";
}, {
    readonly emailConfirmation: {
        readonly type: "string";
        readonly virtual: true;
    };
}>>> | undefined, init?: ((record: Member) => void) | undefined): Member
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ ...
const permitted: Partial<Pick<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly password: "string";
    readonly inviteCode: "string";
}, {
    readonly emailConfirmation: {
        readonly type: "string";
        readonly virtual: true;
    };
}>>, "email" | "emailConfirmation">>
permitted
, password?: string | null | undefinedpassword: "secret" });
await const member: Membermember.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
(); // false: "Email confirmation doesn't match Email"
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const member: Membermember.Model.toJSON(): Record<string, unknown>
The loaded attributes as JSON-ready values (dates as ISO strings), without the Model's `hiddenAttributes`, the virtual attributes its `confirmation` rules read, or its secrets: each secure password, its confirmation, challenge and digest, and each secure token (#355), for `Response.json(record)`.
toJSON
().unknownemailConfirmation); // undefined: never sent back
  • A mismatch is an error on the confirmation, “Email confirmation doesn’t match Email”, so a form shows it beside the second field.
  • A null confirmation passes, so code that sets the email alone needs no confirmation. Add presence to the confirmation to require it.
  • caseSensitive: false ignores case.
  • Without the virtual attribute, the rule throws InvalidModel, naming the attribute to declare.
  • toJSON() leaves the confirmation out, so Response.json(member) never sends it back.

Comparing with another attribute

Give comparison a function of the record to compare with another attribute, as Event does:

import { class EventEvent } from "./models/event";

const const at: Dateat = new 
var Date: DateConstructor
new (value: number | string | Date) => Date (+4 overloads)
Date
("2026-05-01T10:00:00Z");
const const event: Eventevent = class EventEvent.
build<typeof Event>(this: typeof Event, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly startsAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly endsAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Event) => void) | undefined): Event
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ startsAt?: Date | undefinedstartsAt: const at: Dateat, endsAt?: Date | undefinedendsAt: const at: Dateat });
await const event: Eventevent.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
(); // false: "Ends at must be greater than 2026-05-01T10:00:00.000Z"

When the function returns null, that bound is skipped. Validate the other attribute’s presence to report it.

Raising instead of collecting errors

Pass strict: true, as Invoice does, for a value only a bug in your own code could set. A failing rule then throws StrictValidationFailed with its full message, instead of adding an error:

import { class InvoiceInvoice } from "./models/invoice";

const const invoice: Invoiceinvoice = class InvoiceInvoice.
build<typeof Invoice>(this: typeof Invoice, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly total: {
        readonly type: "integer";
        readonly null: false;
    };
    readonly currency: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Invoice) => void) | undefined): Invoice
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ total?: number | undefinedtotal: 1200, currency?: string | undefinedcurrency: "GBP" });
await const invoice: Invoiceinvoice.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
(); // throws StrictValidationFailed: "Currency is not included in the list"

isValid(), save(), and saveOrThrow() all throw it, and the validations after it don’t run. To throw an error class of your own, pass the class as strict, such as strict: UnknownCurrency. It’s made with the same message.

Validating only when creating or updating

Pass on: "create" to run a rule only when a record is created, as Member does with password. By default, a rule runs on every save.

A new record is validated in the "create" context, and a saved one in "update". A rule with on runs only in the contexts it names, so password is checked when a member is created, and not when one is updated. To name several contexts, pass a list, such as on: ["create", "signup"].

exceptOn works the other way. The rule runs in every context except the ones it names.

Naming your own contexts

List a step of your own, such as a signup form, in the Model’s static validationContexts, with as const, as Member does. Then pass it to isValid or save:

import { class MemberMember } from "./models/member";

const const member: Membermember = class MemberMember.
build<typeof Member>(this: typeof Member, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly password: "string";
    readonly inviteCode: "string";
}, {
    readonly emailConfirmation: {
        readonly type: "string";
        readonly virtual: true;
    };
}>>> | undefined, init?: ((record: Member) => void) | undefined): Member
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ email?: string | undefinedemail: "jane@example.com", password?: string | null | undefinedpassword: "secret" });
await const member: Membermember.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
("signup"); // false: invite code can't be blank
const member: Membermember.inviteCode: string | nullinviteCode = "WELCOME"; await const member: Membermember.Model.save(options?: SaveOptions): Promise<boolean>
Inserts a new record or updates a persisted one; `false` if it's invalid, a callback aborted, or a record it destroys refused (#37). `context` validates it in that context (`"signup"`), as `isValid(context)` does.
save
({ SaveOptions.context?: ValidationContexts<ValidationContext> | undefined
Validate in this context (`"signup"`), or these, in place of `"create"` or `"update"`.
context
: ["create", "signup"] }); // the create rules and the signup ones

Rules without on run in every context. A context you pass takes the place of "create" or "update", so the on: "create" rules don’t run. To run both, pass both, as the example does.

"create" and "update" are always there, so list only your own. A context the Model doesn’t list is a compile error in on and exceptOn. Passed to isValid or save, it throws TypeError.

Validating associated records in a context

When you pass a context of your own, the records validated with the owner are validated in it too. These are the records checked by validatesAssociated, and the records saved with their owner. With "create" or "update", each record uses its own: a new record is validated in "create" even when its owner is updated. A list that holds a context of your own reaches them whole, so ["create", "signup"] runs the on: "create" rules of related records that are already saved, too.

Validating associated records

Call this.validatesAssociated, as Playlist does, to validate an association’s records with their owner:

import { class PlaylistPlaylist } from "./models/playlist";

const const playlist: Playlistplaylist = class PlaylistPlaylist.
build<typeof Playlist>(this: typeof Playlist, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Playlist) => void) | undefined): Playlist
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ name?: string | undefinedname: "Road trip" });
const const track: Tracktrack = const playlist: Playlistplaylist.Playlist.tracks: () => HasManyCollection<Track, ScopesOf<typeof Track>>tracks().
Relation<Track, ScopesOf<typeof Track>>.build(attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly playlistId: {
        readonly type: "string";
        readonly null: false;
    };
    readonly title: {
        readonly type: "string";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>>, init?: ((record: Track) => void) | undefined): Track
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ title?: string | undefinedtitle: "" });
await const playlist: Playlistplaylist.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
(); // false: "Tracks is invalid"
const track: Tracktrack.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.fullMessages(): string[]
Every message with its attribute's human name first: "Email can't be blank".
fullMessages
(); // ["Title can't be blank"]

An invalid track makes its playlist invalid, with a “Tracks is invalid” error, and keeps its own errors. If the association isn’t loaded, validating the playlist loads it, with one query. A record marked for destruction isn’t validated. Records built through an association are validated with their owner even without validatesAssociated.

validatesAssociated takes if, unless, on, exceptOn, message, and strict, as validates does. The association’s name is typed, so a misspelled one is a compile error.

You can declare validatesAssociated on both sides of an association. A record that’s already being validated counts as valid, so validating either side finishes.

Reading errors

A record’s errors hold each failed rule:

import { class AccountAccount } from "./models/account";

const const account: Accountaccount = class AccountAccount.
build<typeof Account>(this: typeof Account, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly email: {
        readonly type: "string";
        readonly null: false;
    };
    readonly handle: {
        readonly type: "string";
        readonly null: false;
    };
    readonly plan: "string";
    readonly seats: "integer";
    readonly website: "string";
    readonly isCompany: "boolean";
    readonly companyName: "string";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Account) => void) | undefined): Account
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ email?: string | undefinedemail: "", handle?: string | undefinedhandle: "a!" });
await const account: Accountaccount.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
(); // false
const account: Accountaccount.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.get(attribute: string): string[]
The messages for one attribute (always an array).
get
("email"); // ["can't be blank"]
// "needs at least 3 characters" is ApplicationRecord's tooShort message, not the built-in one. const account: Accountaccount.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.fullMessages(): string[]
Every message with its attribute's human name first: "Email can't be blank".
fullMessages
(); // ["Email can't be blank", "Handle needs at least 3 characters", …]
const account: Accountaccount.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.toArray(): ValidationError[]
Every error as `{ attribute, type, message }`, with its `values` when it has some (copies).
toArray
(); // [{ attribute: "email", type: "blank", message: "can't be blank" }, …]
var console: Consoleconsole.Console.log(...data: any[]): void (+1 overload)
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(const account: Accountaccount.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.size: numbersize); // 5

Printing errors, in the console or a log, lists each failure’s attribute, type, and message. fullMessages() puts the attribute’s name in front, so createdAt reads as “Created at”. Errors on the record as a whole go on "base", and read without a prefix.

An error with a number in its message, such as tooShort, has it in toArray() too:

{ attribute: "handle", type: "tooShort", message: "needs at least 3 characters", values: { count: 3 } }

Adding errors

Add errors in a beforeValidation or afterValidation callback for a rule the validators don’t cover, as Booking does. A record with any errors is invalid:

import { class BookingBooking } from "./models/booking";

const const startsAt: DatestartsAt = new 
var Date: DateConstructor
new (value: number | string | Date) => Date (+4 overloads)
Date
("2026-05-03T10:30:00Z"); // a Sunday
const const booking: Bookingbooking = class BookingBooking.
build<typeof Booking>(this: typeof Booking, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly startsAt: {
        readonly type: "datetime";
        readonly null: false;
    };
    readonly endsAt: {
        readonly type: "datetime";
        readonly null: false;
    };
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Booking) => void) | undefined): Booking
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ startsAt?: Date | undefinedstartsAt, endsAt?: Date | undefinedendsAt: new
var Date: DateConstructor
new (value: number | string | Date) => Date (+4 overloads)
Date
("2026-05-03T11:30:00Z") });
await const booking: Bookingbooking.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
(); // false
const booking: Bookingbooking.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.toArray(): ValidationError[]
Every error as `{ attribute, type, message }`, with its `values` when it has some (copies).
toArray
();
// [{ attribute: "startsAt", type: "onTheHour", message: "must be on the hour" }, // { attribute: "base", type: "invalid", message: "The room is closed on Sundays" }] const booking: Bookingbooking.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.fullMessages(): string[]
Every message with its attribute's human name first: "Email can't be blank".
fullMessages
(); // ["Starts at must be on the hour", "The room is closed on Sundays"]

errors.add takes the attribute, or "base", then either a type or a message. A type takes its message from the Model’s errorMessages, as onTheHour does. See Changing error messages. A message is used as written, and its type is "invalid".

To fill in a placeholder, pass its value with the type:

account.errors.add("handle", { type: "tooShort", count: 3 });

To give a message and a type, pass the type as an option:

account.errors.add("handle", "is reserved", { type: "reserved" });

Each validation run, from isValid(), save(), or saveOrThrow(), starts by clearing errors. So an error added outside a validation callback is gone by the next save.

Changing error messages

Pass message to validates to change one validation’s message, or call this.errorMessages in your app’s base class to change a message for every Model, as ApplicationRecord does with tooShort:

Each key is a built-in error type, or a type of your own. A message with a count, such as tooShort, can have a form for one and a form for any other count.

A Model’s own messages win over the base class’s, and a later call’s over an earlier one’s. Messages under attributes apply to one attribute, as Product’s do. Each message is looked up when you read it:

import { class ProductProduct } from "./models/product";

const const product: Productproduct = class ProductProduct.
build<typeof Product>(this: typeof Product, attributes?: Partial<AttributeProperties<OverriddenSpecs<{
    readonly id: {
        readonly type: "string";
        readonly null: false;
        readonly generateId: true;
    };
    readonly name: {
        readonly type: "string";
        readonly null: false;
    };
    readonly priceCents: {
        readonly type: "integer";
        readonly null: false;
    };
    readonly createdAt: "datetime";
}, Readonly<Record<string, false | AttributeOverride>> | undefined>>> | undefined, init?: ((record: Product) => void) | undefined): Product
A new, unsaved record of this Relation's Model, handed to `init` first if it's given. Nothing awaits `init`, so one that returns a promise throws `TypeError`. Built through a hasMany, it joins the association, and saving the owner saves it too (autosave).
build
({ name?: string | undefinedname: "", priceCents?: number | undefinedpriceCents: 0 });
await const product: Productproduct.Model.isValid(context?: ValidationContexts): Promise<boolean>
Runs every validation, filling `errors` from scratch; `true` if there are none. A context (`"signup"`), or several, replaces the record's own: `"create"` while it's new, `"update"` once it's saved. Rules declared `on` another context don't run.
isValid
(); // false
const product: Productproduct.Model.errors: Errors
The errors from the last validation run.
errors
.Errors.fullMessages(): string[]
Every message with its attribute's human name first: "Email can't be blank".
fullMessages
();
// ["Name needs a name customers will see", // "Name needs at least 3 characters", // "Price must be more than 0"] class ProductProduct.Model.humanAttributeName(attribute: string): string
An attribute's name as error messages show it: from `humanAttributeNames`, or "Created at".
humanAttributeName
("priceCents"); // "Price"

Naming attributes

fullMessages() starts each message with the attribute’s name, made from the attribute itself: createdAt reads as “Created at”. To use another name, call this.humanAttributeNames, as the examples above do. Call it in the base class for every Model, or in a Model for its own attributes.

In a Model, attributes and humanAttributeNames can only name the Model’s attributes, its associations, and "base", so a misspelled name is a compile error. Names in the base class can be any attribute: a Model without that attribute ignores them.

Filling in placeholders

A message can show these values:

  • %{count}: the rule’s number or bound, such as the minimum of tooShort or the bound of greaterThan. A Date bound shows as an ISO string. A bound’s function that returns a filtered attribute’s value shows [FILTERED].
  • %{attribute}: the attribute’s name, as fullMessages() shows it.
  • %{model}: the Model’s name in words, so BlogPost reads as “Blog post”. It’s the class name, unless the Model sets static modelName.
  • %{value}: the attribute’s value. A filtered attribute shows [FILTERED].

A value passed to errors.add with the type, such as count, fills in the placeholder of the same name.

Looking messages up

For each error, the first message found is used:

  1. A message given to validates or errors.add.
  2. The Model’s message for the attribute and type, then its message for the type.
  3. The same for each class the Model extends, your base class included.
  4. The built-in English message.

A type with no message anywhere throws a TypeError when the error is added.

Finding a built-in message

Each error type has a built-in message. To replace one, use its type as the key in errorMessages:

Type Added by Message
blank presence, and comparison for a blank value can’t be blank
present absence must be blank
invalid format and an invalid autosaved association is invalid
inclusion inclusion is not included in the list
exclusion exclusion is reserved
tooShort length: { minimum } is too short (minimum is %{count} characters)
tooLong length: { maximum } is too long (maximum is %{count} characters)
wrongLength length: { is } is the wrong length (should be %{count} characters)
notANumber numericality is not a number
notAnInteger numericality: { onlyInteger } must be an integer
greaterThan numericality or comparison: { greaterThan } must be greater than %{count}
greaterThanOrEqualTo numericality or comparison: { greaterThanOrEqualTo } must be greater than or equal to %{count}
lessThan numericality or comparison: { lessThan } must be less than %{count}
lessThanOrEqualTo numericality or comparison: { lessThanOrEqualTo } must be less than or equal to %{count}
equalTo comparison: { equalTo } must be equal to %{count}
otherThan comparison: { otherThan } must be other than %{count}
passwordTooLong a secure password longer than its algorithm allows is too long
accepted acceptance must be accepted
confirmation confirmation, on the confirming attribute doesn’t match %{attribute}
taken uniqueness has already been taken
required a belongsTo whose record doesn’t exist must exist
restrictDependentDestroy a has-one with dependent: "restrictWithError" Cannot delete record because a dependent %{record} exists
restrictDependentDestroy a has-many with dependent: "restrictWithError" Cannot delete record because dependent %{record} exist

With a count of 1, the three length messages say “1 character”. restrictDependentDestroy goes on "base", and %{record} is the association’s name in lowercase. To replace it, give both forms: restrictDependentDestroy: { hasOne: "…", hasMany: "…" }.

Last updated on