Cross-Field Validation in Ecto Changesets
Validate relationships between multiple fields in Ecto changesets using custom validate/2 logic.
18 Nov 2026, 04:55 UTC

The problem: one field is not enough
Imagine an event form with a start time and an end time. The end time must come after the start time, but Ecto's built-in validations—such as validate_format/3 or validate_number/3—inspect a single attribute at a time. They have no visibility into sibling fields. If you rely only on the changeset DSL, a user can submit an end time that precedes the start time and the changeset will still report valid? as true.
The useful takeaway: changesets are still the right place for this rule. You just write the cross-field check yourself in validate/2, rather than expecting a built-in macro to infer it.
How changesets handle input by default
An Ecto changeset is an immutable struct that carries the data being validated, the permitted changes, and any error messages. When external input arrives—usually as a map of strings from a form or JSON request—you run it through Ecto.Changeset.cast/3. Cast converts values to the types declared in your schema and discards fields you did not mark as writable.
After casting, Ecto.Changeset.validate/2 runs validation functions. Each function receives the changeset and returns a new changeset. Because the struct is immutable, you can stack validators and inspect errors before anything touches the database.
Worked example: end time after start time
Assume you have an Elixir project with Ecto and a configured Repo. Generate a migration in your project directory:
mix ecto.gen.migration create_events
Edit the migration file so it resembles this, replacing MyApp with your application name:
defmodule MyApp.Repo.Migrations.CreateEvents do
use Ecto.Migration
def change do
create table(:events) do
add :title, :string
add :starts_at, :naive_datetime
add :ends_at, :naive_datetime
timestamps()
end
end
end
Run the migration against your development or test database. This changes state, so avoid running it against production data without a backup:
mix ecto.migrate
Now define the schema and changeset. The custom validator reads both fields, preferring the pending change over the persisted value:
defmodule MyApp.Events.Event do
use Ecto.Schema
import Ecto.Changeset
schema "events" do
field :title, :string
field :starts_at, :naive_datetime
field :ends_at, :naive_datetime
timestamps()
end
def changeset(event, attrs) do
event
|> cast(attrs, [:title, :starts_at, :ends_at])
|> validate_required([:title, :starts_at, :ends_at])
|> validate_end_after_start()
end
defp validate_end_after_start(changeset) do
starts_at = get_change(changeset, :starts_at) || get_field(changeset, :starts_at)
ends_at = get_change(changeset, :ends_at) || get_field(changeset, :ends_at)
if starts_at and ends_at and ends_at <= starts_at do
add_error(changeset, :ends_at, "must be after the start time")
else
changeset
end
end
end
Open an IEx session in your project directory and test both directions. Replace the module name with yours:
# Invalid: end before start
attrs = %{"title" => "Meeting", "starts_at" => "~N[2026-12-04 09:00:00]", "ends_at" => "~N[2026-12-04 08:00:00]"}
changeset = MyApp.Events.Event.changeset(%MyApp.Events.Event{}, attrs)
IO.inspect(changeset.valid?, label: "valid?")
IO.inspect(changeset.errors, label: "errors")
Check that valid? is false and that errors contains an entry for :ends_at. Then submit a valid pair where the end time is later and confirm valid? is true. Do not assume the cast succeeded; inspect changeset.changes to confirm the strings became NaiveDateTime structs.
Trade-offs and limitations
- No cross-field DSL. Ecto does not infer that one attribute depends on another. You must write the conditional logic and call
add_error/3manually. - Check both change and field. Use
get_change/2for incoming values and fall back toget_field/2for persisted values, otherwise updates can ignore existing data. - Keep it cheap. Avoid repository queries or slow computations inside
validate/2. Changesets run in the request path; expensive checks belong in a service layer before you build the changeset. - Immutability means verbosity. Every validator returns a new changeset, which is explicit but can feel repetitive compared to mutating an error object in place.
Practical verification
After editing your changeset, run your test suite or an IEx sanity check covering three cases: both fields missing, end time before start time, and end time after start time. Assert on changeset.valid? and the shape of changeset.errors rather than on database side effects. If the errors appear under the expected field, your form or controller can render them directly.
Closing
Use built-in validators for single-field rules, and reserve custom validate/2 logic for relationships between fields. Keep changesets pure, validate early, and inspect errors before calling insert/2 or update/2.