---
title: Validations
description: "Check a record before it’s saved, and see why an invalid one wasn’t."
seo:
  description: "Validate Active Record records before saving: presence, length, format, uniqueness, numericality, and more, with contexts, custom rules, and error messages."
---

## 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:

```ts account.ts
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",
    });
  }
}
```

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

export class Event extends ApplicationRecord {
  static {
    this.validates("endsAt", { comparison: { greaterThan: (event) => event.startsAt } });
  }
}
```

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

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

```ts member.ts
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" });
  }
}
```

```ts playlist.ts
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");
  }
}
```

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

export class Track extends ApplicationRecord {
  static {
    this.validates("title", { presence: true });
  }
}
```

```ts booking.ts
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");
      }
    });
  }
}
```

```ts product.ts
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 } });
  }
}
```

```ts application-record.ts
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" });
  }
}
```

```ts schema.ts
// 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"]> {}
}
```

```sql D1
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
);
```

```sql Postgres
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()`:

```ts
import { Account } from "./models/account";

const account = Account.build({
  email: "jane@example.com",
  handle: "jane",
  plan: "free",
  seats: 1,
});
const valid = await account.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](#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](#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](#finding-a-built-in-message) lists them all, and [Changing error messages](#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](/enums#reading-and-assigning-other-values) 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-types#storing-exact-numbers-days-and-times) 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](#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](/models#adding-virtual-attributes), since the table needn’t keep it.
- **`confirmation`** compares the attribute with a [virtual attribute](/models#adding-virtual-attributes) named for it, such as `emailConfirmation`. See [Confirming a value](#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.

> **Compared with Rails**
>
> Rails treats `false` as blank, so it passes `absence`. Here `false` passes `presence`, so it fails `absence`.
>
> Rails’ `acceptance` lets `nil` pass, since its form helpers send `"0"` for an unticked checkbox. A plain HTML checkbox sends nothing, so here `null` fails.
>
> Rails’ `allow_blank` also skips `false`, `[]`, and `{}`. Here `allowBlank` skips what `presence` fails: `null` and a string that’s only whitespace.

:::warning[Uniqueness isn’t a guarantee]
Two requests can both check that an email is free, then both insert it. `uniqueness` gives a friendly error early, but only a UNIQUE index in the table prevents duplicates, so declare both. When the index catches a duplicate, the save throws [`RecordNotUnique`](/errors#constraint-errors). For attributes you create with [`createOrFindBy`](/persistence#creating-records-from-concurrent-requests), declare only the index.
:::

### 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`:

```ts
import { Member } from "./models/member";

const form = { email: "jane@example.com", emailConfirmation: "jane@exmaple.com" };
const permitted = Member.permit(form, "email", "emailConfirmation");
const member = Member.build({ ...permitted, password: "secret" });
await member.isValid(); // false: "Email confirmation doesn't match Email"
console.log(member.toJSON().emailConfirmation); // 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.

> **Compared with Rails**
>
> Rails’ `confirmation` defines `email_confirmation` for you, as a plain accessor. Here you declare it as a virtual attribute, so it’s typed, cast, and taken by `permit`. Like Rails, `toJSON()` never sends it.

### Comparing with another attribute

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

```ts
import { Event } from "./models/event";

const at = new Date("2026-05-01T10:00:00Z");
const event = Event.build({ startsAt: at, endsAt: at });
await event.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.

> **Compared with Rails**
>
> Rails names the other attribute with a symbol, `comparison: { greater_than: :starts_at }`. Here a function does it, so the attribute’s name is typed.

### 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:

```ts
import { Invoice } from "./models/invoice";

const invoice = Invoice.build({ total: 1200, currency: "GBP" });
await invoice.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`:

```ts
import { Member } from "./models/member";

const member = Member.build({ email: "jane@example.com", password: "secret" });
await member.isValid("signup"); // false: invite code can't be blank
member.inviteCode = "WELCOME";
await member.save({ 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`.

:::note
List contexts on each Model. A Model’s subclass shares its list, and an abstract base class can’t have one.
:::

### 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](/autosaving#saving-a-graph). 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.

> **Beyond Rails**
>
> Rails accepts any context name, so a misspelled one quietly runs none of its rules. Here a Model lists its contexts, and a name it doesn’t list is a compile error or a `TypeError`.

> **Compared with Rails**
>
> `valid?(:signup)` is `isValid("signup")`, `save(context: :signup)` is `save({ context: "signup" })`, and `except_on:` is `exceptOn`.

## Validating associated records

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

```ts
import { Playlist } from "./models/playlist";

const playlist = Playlist.build({ name: "Road trip" });
const track = playlist.tracks().build({ title: "" });
await playlist.isValid(); // false: "Tracks is invalid"
track.errors.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](/autosaving#saving-a-graph) 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.

:::note
Each track is validated with its own rules and callbacks, so a `uniqueness` rule on a track sends a query for every track. Use `validatesAssociated` on associations that stay small.
:::

> **Compared with Rails**
>
> When `validates_associated` and autosave both check a record, Rails validates it twice and adds “is invalid” twice. Here it’s validated once, with one error.
>
> Rails’ `validates_associated` on both sides of an association recurses until the stack overflows. Here the record already being validated counts as valid.

## Reading errors

A record’s `errors` hold each failed rule:

```ts
import { Account } from "./models/account";

const account = Account.build({ email: "", handle: "a!" });
await account.isValid(); // false

account.errors.get("email"); // ["can't be blank"]
// "needs at least 3 characters" is ApplicationRecord's tooShort message, not the built-in one.
account.errors.fullMessages(); // ["Email can't be blank", "Handle needs at least 3 characters", …]
account.errors.toArray(); // [{ attribute: "email", type: "blank", message: "can't be blank" }, …]
console.log(account.errors.size); // 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:

```ts
{ 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:

```ts
import { Booking } from "./models/booking";

const startsAt = new Date("2026-05-03T10:30:00Z"); // a Sunday
const booking = Booking.build({ startsAt, endsAt: new Date("2026-05-03T11:30:00Z") });
await booking.isValid(); // false

booking.errors.toArray();
// [{ attribute: "startsAt", type: "onTheHour", message: "must be on the hour" },
//  { attribute: "base", type: "invalid", message: "The room is closed on Sundays" }]
booking.errors.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](#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:

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

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

```ts
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.

> **Compared with Rails**
>
> Rails’ `errors.add(:starts_at, :on_the_hour)` is `errors.add("startsAt", { type: "onTheHour" })` here, since a type and a message are both strings in TypeScript. When Rails is given a message instead, that text is the type too; here the type is `"invalid"`. Rails’ `message:` and `strict:` options and its procs aren’t here.

## 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](#finding-a-built-in-message), 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:

```ts
import { Product } from "./models/product";

const product = Product.build({ name: "", priceCents: 0 });
await product.isValid(); // false

product.errors.fullMessages();
// ["Name needs a name customers will see",
//  "Name needs at least 3 characters",
//  "Price must be more than 0"]
Product.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.

:::note
`Product.humanAttributeName("priceCents")` returns the same name, for a form’s label.
:::

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](/serialization#filtering-attributes)’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`](/models#naming-models).
- **`%{value}`**: the attribute’s value. A [filtered attribute](/serialization#filtering-attributes) 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](/passwords-and-tokens) 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: "…" }`.

> **Compared with Rails**
>
> Rails looks messages up in its locale files, in nearly the same order: the Model’s, then its ancestors’, then the shared ones. Among the shared ones, Rails tries a message for the type before one for the attribute. Your base class tries the attribute’s first, as every class does. Active Record keeps messages on the classes instead, so a Model’s messages sit next to its validations. Their keys are Active Record’s error types, in camelCase. Rails shows “Translation missing” for a type with no message, where Active Record throws when the error is added. Messages in other languages aren’t here yet.
