Utility.Validators behaviour (Portico/Z v0.1.0)

Behaviour and helper functions for validating values.

NOTE: Functions in this module get auto-imported into any ZSchemas module.

Validator Behaviour

The "validator" behaviour specifies a method by which any kind of data can be validated and returned in a consistent format. This is handy because it allows us to define modules that perform different kinds of validations, but to use them all in the same way, eg. in Ecto changesets.

Validators NOT to Implement

Don't implement an email validator. There are a few reasons, but our top two are:

  1. It's basically impossible
  2. Browsers already have an email validator!

Instead of validating in the back-end, just use Phoenix.HTML.Form.email_input/3, which will have the browser validate the email input before the form even gets submitted!

Link to this section Summary

Link to this section Functions

Link to this function

validate_change_with(changeset, field, validator, args \\ [])

Use any module implementing the Elixir.Utility.Validators behaviour as a validator for Ecto.Changeset.validate_change/3.

Typical Usage

Typically, this function would be used in an Ecto Changeset pipeline. For example:

model
|> cast(attrs, [:url, :other_field])
|> validate_required([:url, :other_field])
|> validate_change_with(:url, Utility.Validators.UrlValidator)

args get passed to the validator module for use in validation, if necessary.

See Utility.Validators.UrlValidator for an example module implementing this behaviour.

Link to this section Callbacks

Link to this callback

validate(value, args)

Specs

validate(value :: term(), args :: Keyword.t()) :: :ok | {:error, String.t()}