Skip to content

Instantly share code, notes, and snippets.

@slashdotdash
Last active December 30, 2019 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slashdotdash/2ba9307b22314b55d685e7cc4e2ee567 to your computer and use it in GitHub Desktop.
Save slashdotdash/2ba9307b22314b55d685e7cc4e2ee567 to your computer and use it in GitHub Desktop.
Use Ecto Changeset to validate a command
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