Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Ecto Schemas and Queries

Changesets: Casting, Validation and Constraints

Master Ecto changesets: cast and whitelist params, run built-in and custom validations, handle unique constraint errors, and use separate changesets per use case.

A changeset is Ecto's way of describing a change to data before it is saved. It holds the original data, the proposed changes, a list of validation errors and a valid? flag. Every form in a Phoenix app passes through one: the user's raw, untrusted params go in; either a clean change or a list of friendly errors comes out.

This lesson covers cast, the built-in validations, custom validations, database constraints and how to write several changesets for one schema. You saw changesets in forms and to_form; now you will learn how they work.

Ecto needs Elixir, so the Elixir code is read-only. TryIts model casting and validation in JavaScript.

cast: whitelist and convert

ELIXIR
def changeset(user, attrs) do
  user
  |> cast(attrs, [:name, :email, :age])
  |> validate_required([:name, :email])
end

cast(data, params, permitted) does three things:

  1. Whitelists: only fields in permitted are taken. A forged is_admin param is silently ignored.
  2. Converts: string params become the schema types: "42" becomes 42 for an integer field. If conversion fails, the changeset gets an error like "is invalid".
  3. Tracks changes: only values that differ from the existing data are stored in changeset.changes.
ELIXIR
cs = User.changeset(%User{}, %{"name" => "Ada", "email" => "", "age" => "abc", "is_admin" => "true"})
cs.valid?    # false
cs.changes   # %{name: "Ada"}
cs.errors    # [age: {"is invalid", ...}, email: {"can't be blank", ...}]

Empty strings are cast to nil by default, which is why a blank email counts as missing.

Built-in validations

ELIXIR
|> validate_required([:name, :email])
|> validate_length(:name, min: 2, max: 60)
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have an @")
|> validate_number(:age, greater_than_or_equal_to: 13, less_than: 130)
|> validate_inclusion(:role, ["reader", "author"])
|> validate_exclusion(:username, ["admin", "root"])
|> validate_acceptance(:terms)
|> validate_confirmation(:password, message: "does not match")
|> validate_change(:title, fn :title, title -> ... end)

validate_confirmation compares password and password_confirmation params. Each function adds an error to changeset.errors for the failing field, with a message and metadata used for translations.

Custom validations

A custom validation is a function that takes a changeset and returns one:

ELIXIR
defp validate_no_shouting(changeset, field) do
  validate_change(changeset, field, fn _, value ->
    if value == String.upcase(value) and String.length(value) > 4 do
      [{field, "please don't shout"}]
    else
      []
    end
  end)
end

Use get_field/2 to read a value from changes or data, and add_error/3 for cross-field rules:

ELIXIR
defp validate_dates(changeset) do
  starts = get_field(changeset, :starts_on)
  ends = get_field(changeset, :ends_on)

  if starts && ends && Date.compare(ends, starts) == :lt do
    add_error(changeset, :ends_on, "must be after the start date")
  else
    changeset
  end
end

You can also compute fields: put_change(changeset, :slug, slugify(title)), usually only when the changeset is valid.

Constraints

Some rules can only be checked by the database, such as uniqueness (two people may submit the same email at the same moment). Declare the constraint in the migration, then tell the changeset to turn the database error into a normal changeset error:

ELIXIR
|> unique_constraint(:email)
|> foreign_key_constraint(:author_id)
|> check_constraint(:price, name: :price_must_be_positive)

Without unique_constraint, a duplicate would raise Ecto.ConstraintError. With it, Repo.insert returns {:error, changeset} with "has already been taken". Remember: unsafe_validate_unique/3 only gives an early hint; the constraint is what guarantees correctness.

One schema, several changesets

A form to register is not the same as a form to change a password or an admin edit. Write a changeset per use case:

ELIXIR
def registration_changeset(user, attrs) do
  user
  |> cast(attrs, [:email, :password])
  |> validate_required([:email, :password])
  |> validate_length(:password, min: 12)
  |> unique_constraint(:email)
end

def profile_changeset(user, attrs) do
  user |> cast(attrs, [:name, :bio]) |> validate_length(:bio, max: 500)
end

def admin_changeset(user, attrs) do
  user |> cast(attrs, [:role, :active])
end

Each one permits only the fields that screen is allowed to touch.

Schemaless and embedded changesets

You can validate data that is not a table, such as a contact form, with a schemaless changeset: {%{}, %{email: :string, message: :string}} |> cast(params, [:email, :message]). Ecto also supports embeds_one/embeds_many for structured JSON inside a column, and Ecto.Changeset.apply_action/2 to turn a valid changeset into a struct without saving.

Casting and validating, modeled

JS cast, validate, collect errors

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

No output.

is_admin never appears in the changes because it was not permitted, and "abc" could not become an integer.

A unique constraint, modeled

JS Turning a database error into a changeset error

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

No output.

The mapping table plays the role of unique_constraint(:email): without it the exception would escape.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main security role of cast/3?

    Only permitted fields are copied, so extra params like is_admin are ignored.
  2. 2. Why use unique_constraint when validate_unique-style checks exist?

    Two simultaneous requests can both pass a pre-check; the unique index plus unique_constraint handle the race.
  3. 3. What does add_error/3 do?

    It marks the changeset invalid with a message attached to the field.
  4. 4. Why write more than one changeset function per schema?

    A registration, profile edit and admin edit each permit and validate different fields.

Summary

  • A changeset holds data, changes, errors and valid?; cast whitelists and converts params.
  • Use built-in validators, custom validate_change, get_field and add_error for your rules.
  • Back uniqueness and references with database constraints and tell the changeset with unique_constraint and friends.
  • Write one changeset per use case so each form can only change what it should.

Next: Associations, preloading and contexts