Ecto Changesets: Validation and Selective Persistence
Ecto.Changeset is a pure Elixir struct for casting, validating, and tracking changes before persistence. It accumulates errors and converts database constraint violations into changeset errors.
23 Jul 2026, 00:28 UTC

The Problem: Validation Logic Sprawling Across Your App
When a web request reaches your Phoenix controller, raw parameters must become a valid database record. Without a structured mechanism, validation logic scatters across controllers, schema functions, and the database itself. The result is duplicated checks, inconsistent error messages, and UPDATE statements that overwrite columns you did not intend to change.
Thesis: Changesets Are Pure Data Until You Persist Them
Ecto.Changeset is not an object with side-effecting methods. It is an Elixir struct that holds the original data, a map of changes, and a list of accumulated errors. You can build, inspect, and pass a changeset without touching the database. Only when you hand it to Repo.insert/2 or Repo.update/2 does Ecto generate SQL.
How the Pipeline Works
Start with an empty or existing schema struct, then cast only the fields you expect. Add required-field checks, format validations, and database constraints. Each function returns a new changeset; nothing is mutated.
Key Behaviors
- Selective SQL writes: Ecto generates UPDATE statements only for fields in the
changesmap, reducing write amplification. - Composable errors: Validation failures accumulate in a keyword list keyed by field, so a form can display every problem at once.
- Database constraint conversion:
unique_constraint/2turns a Postgres duplicate-key violation into a changeset error at commit time, without application-level locks.
Worked Example: User Registration with an Embedded Address
This example assumes a Mix project with ecto_sql and a Postgres adapter configured. Run iex inside the project with iex -S mix.
Schema Definition
defmodule MyApp.User do
use Ecto.Schema
embedded_schema do
field :street, :string
field :city, :string
end
schema "users" do
field :email, :string
field :name, :string
embed :address, MyApp.User.Address
end
def changeset(user, params) do
user
|> Ecto.Changeset.cast(params, [:email, :name, address: [:street, :city]])
|> Ecto.Changeset.validate_required([:email, :name])
|> Ecto.Changeset.validate_format(:email, ~r/@/)
|> Ecto.Changeset.cast_embed(:address, validate: true)
|> Ecto.Changeset.unique_constraint(:email)
end
end
Testing in iex
Run these commands in iex -S mix. You need a Postgres database reachable by your Repo if you proceed to the insert step.
iex> user = %MyApp.User{}
iex> cs = MyApp.User.changeset(user, %{email: "bad", name: ""})
iex> cs.changes
iex> cs.errors
iex> cs = Ecto.Changeset.put_change(cs, :name, "Sam")
iex> cs = Ecto.Changeset.put_change(cs, :email, "[contact removed]")
iex> cs = Ecto.Changeset.cast_embed(cs, %{street: "123 Main", city: "NYC"})
iex> cs.changes
iex> cs.errors
Check that cs.changes contains only the fields you passed, and that cs.errors lists validation problems keyed by field. If cs.errors is empty after your edits, the changeset is valid according to the rules you defined.
Database Insert
With a Repo configured, insert the changeset:
iex> MyApp.Repo.insert(cs)
If the email already exists and a unique index is present on users(email), Postgres raises a duplicate-key error that unique_constraint/2 converts into a changeset error under :email.
Trade-Offs and Limitations
- Virtual fields need custom logic: A field such as
:password_confirmationthat is not stored in the database is not cast automatically. Usevalidate_change/3to compare it against:password. - Nested deletes can be chatty:
cast_assoc(..., on_replace: :delete)issues one DELETE per removed row. For bulk operations, manage child rows manually or useon_replace: :updatewhen appropriate. - Constraint errors appear only at commit:
unique_constraint/2does not pre-check the database. You must create the matching unique index in a migration, or the violation will not be caught as a changeset error.
Actionable Next Steps
To verify your setup:
- Generate a migration:
mix ecto.gen.migration add_unique_email_index. - Add
create unique_index(:users, [:email])to the migration and runmix ecto.migrate. - Insert one user, then attempt to insert another with the same email. Confirm the returned tuple is
{:error, changeset}and thatchangeset.errorsincludes:email. - Define an
embedded_schema, usecast_embed/3, and pass nested parameters to confirm nested errors appear under the embed key.
Treating changesets as serializable data structures lets you validate API payloads, GenServer state transitions, or form submissions with the same logic you use for database persistence.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.