We’ve completed the first step of changing the database and we have a Changeset struct with the changes we want to apply. Before we send it off to the database, we want to ensure that the data we’ve got is correct. Ecto provides two tools to help us check the integrity of our data:

  • Validations
  • Constraints

They perform similar functions but differ in the way that they’re implemented. We’ll explore each of them in the rest of this lesson.

Work with validations

Validations are utility functions provided by the Ecto.Changeset module to help check the integrity of our data. If we look at the module documentation, the validation functions are easy to spot because they all start with validate_: validate_required, validate_format, validate_number, and the like. They all take a changeset as the first parameter and return a new changeset with the validation applied. This arrangement lends itself very nicely to working with the pipe operator.

Get hands-on with 1200+ tech skills courses.