EmailEctoType v0.1.4 EmailEctoType View Source

An ecto type that provides easy way of managing email addresses in a database.

Usage

Suppose you define the following schema

defmodule EmailEctoType.Support.Schema do
  @moduledoc false

  use Ecto.Schema

  alias Ecto.Changeset

  embedded_schema do
    field :email, EmailEctoType
  end

  def changeset(%__MODULE__{} = schema, attrs) do
    Changeset.cast(schema, attrs, [:email])
  end
end

Now you can validate an email like this:

iex(1)> alias EmailEctoType.Support.Schema
iex(2)> alias EmailEctoType.Email
iex(3)> changeset = Schema.changeset(%Schema{}, %{email: "asdf@host.com"})
iex(4)> changeset.valid?
true
iex(5)> Ecto.Changeset.apply_changes(changeset)
%Schema{email: %Email{address: "asdf@host.com", user: "asdf", host: "host.com"}}

In case you provide an invalid email it will return an error on casting:

iex(1)> alias EmailEctoType.Support.Schema
iex(2)> changeset = Schema.changeset(%Schema{}, %{email: "asdf@"})
iex(3)> changeset.valid?
false
iex(4)> changeset.errors
[email: {"is invalid", [type: EmailEctoType, validation: :cast]}]

Custom type

You can also define your custom email type using this module:

defmodule EmailEctoType.Support.CustomEmailType do
  @moduledoc false

  use EmailEctoType, validators: []
end

And use it in schema:

defmodule EmailEctoType.Support.SchemaWithCustomType do
  @moduledoc false

  use Ecto.Schema

  alias Ecto.Changeset
  alias EmailEctoType.Support.CustomEmailType

  embedded_schema do
    field :email, CustomEmailType
  end

  def changeset(%__MODULE__{} = schema, attrs) do
    Changeset.cast(schema, attrs, [:email])
  end
end

As we did not specify any validators for an email, it won't fail on invalid strings (see EmailEctoType.Validator for more info):

iex(1)> alias EmailEctoType.Support.SchemaWithCustomType, as: Schema
iex(2)> changeset = Schema.changeset(%Schema{}, %{email: "asdf@"})
iex(3)> changeset.valid?
true