View Source Ecto.Email (Ecto.Email v1.0.0)
An Ecto.Type
for email addresses, using the
:email_validator
library
for validations.
Usage
When creating an email field, the underline column should be specified
as a :string
or a :citext
.
Migration
defmodule Core.Repo.Migrations.CreatePeople do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS citext", ""
create table(:people) do
add :email_address, :citext, null: false
timestamps()
end
end
end
Schema
The schema should specify the field as an Ecto.Email
. 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, Ecto.Email
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
.
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> Ecto.Email.cast("a@b.com")
{:ok, "a@b.com"}
iex> Ecto.Email.cast("a+b@c.com")
{:ok, "a+b@c.com"}
iex> Ecto.Email.cast("a.c.com")
{:error, message: "malformed email address"}
iex> Ecto.Email.cast("12")
{:error, message: "malformed email address"}
iex> Ecto.Email.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
.
iex> assert Ecto.Email.equal?("a@b.com", "a@b.com")
iex> refute Ecto.Email.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 Ecto.Email
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.