Learn how to use Ecto changesets to validate and sanitize data before database operations in Phoenix
Learn how to use Ecto changesets to validate and sanitize data before database operations in Phoenix.
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.
cast
checks permitted fields and their typesvalidate_required
ensures mandatory fields are presentvalidate_length
for minimum name length, validate_format
for emails)unique_constraint
guarantees unique fields (e.g., slug).valid?
and .errors
Product.changeset(%Product{}, %{name: "Diablo 4", console: "pc"})
.changes
to see sanitized, valid data ready for DB insertname
, auto-generate a slug
by downcasing and replacing spaces with dashes)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.