Jeffrey Hicks

Jeffrey Hicks

Platform Eng @R360

12 - Phoenix crash course #12: Ecto changesets

Learn how to use Ecto changesets to validate and sanitize data before database operations in Phoenix

By Daniel Bergholz • Aug 19, 2025

Learn how to use Ecto changesets to validate and sanitize data before database operations in Phoenix.

What is a changeset?

A changeset is a function (generated by Phoenix for each schema) that runs before data gets inserted/updated in the database. It keeps your data safe and valid.

Why use changesets?

  • Ensure only safe, correct data goes into your database (e.g. block random/unsafe fields)
  • Run data type checks, require certain fields, check for uniqueness, etc.

How changesets work

  • cast checks permitted fields and their types
  • validate_required ensures mandatory fields are present
  • Custom validations (e.g., validate_length for minimum name length, validate_format for emails)
  • unique_constraint guarantees unique fields (e.g., slug)

Example usage in IEx

  • Create changesets and test validity/errors with .valid? and .errors
  • Example:
    Product.changeset(%Product{}, %{name: "Diablo 4", console: "pc"})
  • Use .changes to see sanitized, valid data ready for DB insert

Custom transformations

  • You can chain functions (e.g., trim whitespace in name, auto-generate a slug by downcasing and replacing spaces with dashes)
  • These transformations are added to the changeset pipeline before writing to DB

Flexible data sanitizing

  • Add any logic before inserting—e.g., formatting, trimming, generating slugs, rejecting invalid data

Summary

Changesets are the main way to validate and sanitize input before DB writes in Phoenix. Use them to apply business rules, clean data, and prevent bugs or attacks—keeping your database healthy and consistent.

Related

#phoenix-and-elixir #phoenix-crash-course #daniel-bergholz