EctoEmail (EctoEmail v3.0.2)
View SourceAn Ecto.Type
for email addresses, using the
ex_email
library
for validations.
Usage
When creating an email field, the underline column should be specified
as a :string
or a :text
.
Migration
defmodule Core.Repo.Migrations.CreatePeople do
use Ecto.Migration
def change do
create table(:people) do
add :email_address, :string, null: false
timestamps()
end
end
end
Schema
The schema should specify the field as an EctoEmail
. This will
apply automatic validations to the field, though when accessing
relevant structs the data will be returned as String
values.
defmodule Schema.Person do
use Ecto.Schema
import Ecto.Changeset
schema "people" do
field :email_address, EctoEmail
end
def changeset(data \ %__MODULE__{}, attrs) do
data
|> cast(Map.new(attrs), ~w[email_address]a)
end
end
Changesets
Ecto changesets using the Ecto.Enum
type will automatically validate
the format of values.
iex> assert Schema.Person.changeset(email_address: "a@b.com").valid?
iex> assert changeset = Schema.Person.changeset(email_address: "a.at.b.com")
iex> refute changeset.valid?
iex> assert [email_address: {"malformed email address", _}] = changeset.errors
Summary
Functions
Callback implementation for Ecto.Type.cast/1
.
Callback implementation for Ecto.Type.dump/1
Callback implementation for Ecto.Type.embed_as/1
.
Callback implementation for Ecto.Type.equal?/2
. When comparing two email addresses
differing only in case, the addresses are treated as equal.
Callback implementation for Ecto.Type.load/1
Callback implementation for Ecto.Type.type/0
.
Functions
Callback implementation for Ecto.Type.cast/1
.
Casts external input to a string, while validating that the format of the contents.
iex> EctoEmail.cast("a@b.com")
{:ok, "a@b.com"}
iex> EctoEmail.cast("a+b@c.com")
{:ok, "a+b@c.com"}
iex> EctoEmail.cast("a.c.com")
{:error, message: "malformed email address"}
iex> EctoEmail.cast("12")
{:error, message: "malformed email address"}
iex> EctoEmail.cast(12)
{:error, message: "invalid email address"}
iex> assert %Ecto.Changeset{valid?: true} = Schema.Person.changeset(email_address: "a@b.com")
iex> assert %Ecto.Changeset{valid?: false} = Schema.Person.changeset(email_address: "a.b.com")
Callback implementation for Ecto.Type.dump/1
Callback implementation for Ecto.Type.embed_as/1
.
Callback implementation for Ecto.Type.equal?/2
. When comparing two email addresses
differing only in case, the addresses are treated as equal.
iex> assert EctoEmail.equal?("a@b.com", "a@b.com")
iex> assert EctoEmail.equal?("A@B.com", "a@b.com")
iex> refute EctoEmail.equal?("a@b.com", "a@c.com")
Callback implementation for Ecto.Type.load/1
Callback implementation for Ecto.Type.type/0
.
Email address fields using EctoEmail
should use a database column type
capable of working with :string
Ecto type. :string
, :text
, or :citext
are examples of column types useable in migrations.