Search⌘ K

Validating Our Quizzes

Explore validating quiz data in Elixir by building dedicated validator modules. Understand how to handle state isolation and error management with GenServer while validating required and optional fields such as title and mastery. This lesson helps you create robust data checks using pattern matching and custom error responses.

We first need to validate a quiz. We are creating a module per validator, and only add models that take complex user data.

Declaring our module and some core functions

In /lib/mastery/boundary/quiz_validator.ex, we’ll write this code:

C++
defmodule Mastery.Boundary.QuizValidator do import Mastery.Boundary.Validator
def errors(fields) when is_map(fields) do
[ ]
|> require(fields, :title, &validate_title/1)
|> optional(fields, :mastery, &validate_mastery/1)
end
def errors(_fields), do: [{nil, "A map of fields is required"}]

We have a core errors function that does the lion’s share of the work.

  • We have only two fields that have external input, an optional :mastery field and a required :title field.

  • We pipe through those and return the responses. ...