[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
|
||||
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
|
||||
|
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user