[day-02] validate user input
Also improve migration to reflect requirements in validation done through `Ecto.Changeset`.
This commit is contained in:
parent
97af827bc2
commit
d578bc6cf3
@ -1,8 +1,12 @@
|
|||||||
defmodule Wabanex.User do
|
defmodule Wabanex.User do
|
||||||
use Ecto.Schema
|
use Ecto.Schema
|
||||||
|
|
||||||
|
import Ecto.Changeset
|
||||||
|
|
||||||
@primary_key {:id, :binary_id, autogenerate: true}
|
@primary_key {:id, :binary_id, autogenerate: true}
|
||||||
|
|
||||||
|
@fields ~w(name email password)a
|
||||||
|
|
||||||
schema "users" do
|
schema "users" do
|
||||||
field :name, :string
|
field :name, :string
|
||||||
field :email, :string
|
field :email, :string
|
||||||
@ -10,4 +14,14 @@ defmodule Wabanex.User do
|
|||||||
|
|
||||||
timestamps()
|
timestamps()
|
||||||
end
|
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
|
end
|
||||||
|
@ -3,9 +3,9 @@ defmodule Wabanex.Repo.Migrations.CreateUsersTable do
|
|||||||
|
|
||||||
def change do
|
def change do
|
||||||
create table(:users) do
|
create table(:users) do
|
||||||
add :email, :string
|
add :email, :string, null: false
|
||||||
add :name, :string
|
add :name, :string, null: false
|
||||||
add :password, :string
|
add :password, :string, null: false
|
||||||
|
|
||||||
timestamps()
|
timestamps()
|
||||||
end
|
end
|
||||||
|
Loading…
x
Reference in New Issue
Block a user