(no title)
IceDragon200 | 2 years ago
For the email validation I would have used an ecto schema, since most cases you won't just be validating an email address in isolation:
defmodule EmailSchema do
use Ecto.Schema
import Ecto.Changeset
@primary_key false
embedded_schema do
# here is your type validation right off the bat
field :email, :string
end
def validate(email) do
%__MODULE__{}
|> cast(params, [
:email,
])
|> validate_required([
:email,
])
|> validate_change(:email, fn :email, value ->
cond do
not is_email_address?(value) ->
[email: {"invalid email address", [validation: :email]}]
not EmailAddresses.is_available?(value) ->
[email: {"is unavailable", [validation: :email]}]
true ->
[]
end
end)
|> apply_action(:insert)
end
end
case EmailSchema.validate(email) do
{:ok, %{email: email}} ->
{:error, %Ecto.Changeset{} = changeset} ->
changeset.errors[:email]
# Can be all of these in the same list, or be any one depending on the validations
#=> [{"is required", [validation: :required]}]
#=> [{"invalid email address", [validation: :email]}]
#=> [{"is unavailable", [validation: :email]}]
end
No comments yet.