Data Validation

Learn how to test an ecto schema as a data validator.

It’s very common in web applications to do some basic validation of user input in the controller. If easy-to-detect issues are present, the application doesn’t spend time doing work (or calling the database) when there isn’t a chance of success.

The code that we’ve already written in the previous lesson takes input and casts it to the appropriate value, returning errors for any data that can’t be cast or any required missing parameters. This is exactly the kind of basic validation that we’re talking about. We’ll update our code to serve as a validator with some very minor changes. After that, we’ll update our refactored tests to reflect the changes.

Note: We’ve created a playground at the end of this lesson where you can perform your updates as we move along with the lesson.

Testing an ecto schema

As mentioned, our code already does the work we want. The only issue we have now is that the interface isn’t ideal.

Data validator

Our application code isn’t going to want to receive a changeset when the code executes successfully. Ideally, when the input is valid, our validator will return a tuple with :ok and a struct with the fields and values. We’ll still return the changeset with errors when it errors, but inside an error tuple.

There’s one other interface change we should make: renaming the function. Since we’re no longer returning a changeset, we’ll rename the one public function, changeset/1, to instead reflect what the code is doing.

We’ll create a copy of the schema file at the path testing_ecto/lib/schemas/user_validator.ex inside the playground ...