...

/

Validating Our Quizzes

Validating Our Quizzes

Let’s learn how to validate our quizzes.

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:

Press + to interact
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.

Let’s try out a few ...