Last active
December 30, 2019 12:09
-
-
Save slashdotdash/2ba9307b22314b55d685e7cc4e2ee567 to your computer and use it in GitHub Desktop.
Use Ecto Changeset to validate a command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule OpenAccount do | |
defstruct [:account_number, :initial_balance] | |
@types %{ | |
account_number: :string, | |
initial_balance: :integer | |
} | |
def validate(params) do | |
{params, @types} | |
|> Changeset.cast(params, [:account_number, :initial_balance]) | |
|> Changeset.validate_required([:account_number, :initial_balance]) | |
|> Changeset.validate_number(:initial_balance, greater_than: 0) | |
|> case do | |
%Changeset{valid?: true, changes: changes} -> {:ok, changes} | |
%Changeset{errors: errors} -> {:error, errors} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment