Validate Your Data
Explore how to maintain data integrity by using Ecto validations and custom validation functions within changesets. Learn to apply built-in validators like validate_required and validate_length, and create reusable custom validations for more complex rules. Understand how to handle validation errors and present them effectively in your Elixir database applications.
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.
In this example, ...