Skip to content

Instantly share code, notes, and snippets.

@talum
Created May 28, 2019 17:34
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 talum/4769ea2fcc18ad057ac95e09ec8feafd to your computer and use it in GitHub Desktop.
Save talum/4769ea2fcc18ad057ac95e09ec8feafd to your computer and use it in GitHub Desktop.
invoice changeset
defmodule Registrar.Billing.Invoice do
import Ecto.Changeset
def changeset(%Invoice{} = invoice, attrs \\ %{}) do
  invoice
  |> cast(attrs, [
   :amount_due,
   :due_date,
   :scheduled_send_date
  ])
  |> validate_required([
   :amount_due,
   :due_date,
   :scheduled_send_date
  ])
  |> validate_due_date_not_past()
 end
  # Custom validation here, which accepts a changeset, adds a custom error when applicable,
  # and returns the changeset
  defp validate_due_date_not_past(changeset) do
  validate_change(changeset, :due_date, fn _, due_date ->
  now = NaiveDateTime.utc_now()
  case NaiveDateTime.compare(due_date, now) do
   :lt -> [due_date: "cannot be in past"]
  _ -> []
  end
  end)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment