From d578bc6cf317c21c11a3129b7c9a9f056b6c1e0b Mon Sep 17 00:00:00 2001 From: Joao P Dubas Date: Tue, 22 Jun 2021 23:56:07 +0000 Subject: [PATCH] [day-02] validate user input Also improve migration to reflect requirements in validation done through `Ecto.Changeset`. --- lib/wabanex/user.ex | 14 ++++++++++++++ .../20210622015725_create_users_table.exs | 6 +++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/wabanex/user.ex b/lib/wabanex/user.ex index 2403553..562c2b1 100644 --- a/lib/wabanex/user.ex +++ b/lib/wabanex/user.ex @@ -1,8 +1,12 @@ defmodule Wabanex.User do use Ecto.Schema + import Ecto.Changeset + @primary_key {:id, :binary_id, autogenerate: true} + @fields ~w(name email password)a + schema "users" do field :name, :string field :email, :string @@ -10,4 +14,14 @@ defmodule Wabanex.User do timestamps() end + + def changeset(params) do + %__MODULE__{} + |> cast(params, @fields) + |> validate_required(@fields) + |> validate_length(:name, min: 2) + |> validate_length(:password, min: 6) + |> validate_format(:email, ~r/@/) + |> unique_constraint([:email]) + end end diff --git a/priv/repo/migrations/20210622015725_create_users_table.exs b/priv/repo/migrations/20210622015725_create_users_table.exs index 4e0745a..f740879 100644 --- a/priv/repo/migrations/20210622015725_create_users_table.exs +++ b/priv/repo/migrations/20210622015725_create_users_table.exs @@ -3,9 +3,9 @@ defmodule Wabanex.Repo.Migrations.CreateUsersTable do def change do create table(:users) do - add :email, :string - add :name, :string - add :password, :string + add :email, :string, null: false + add :name, :string, null: false + add :password, :string, null: false timestamps() end