Ecto Changeset Date validation

1,485 views
Skip to first unread message

germain baptiste delpy

unread,
Jul 22, 2016, 9:51:33 PM7/22/16
to elixir-ecto
The field :date must be >= date.now. What is the proper way to do that?
I don't see any validate_date function in the Ecto.Changeset documentation.
I like changeset, I want to stick on it, please help!
G.

Andrew Timberlake

unread,
Jul 23, 2016, 9:16:57 AM7/23/16
to elixi...@googlegroups.com
It’s not too difficult to write your own validator,

defmodule MyModel do
#...

schema "mytable" do
field :date, Ecto.Date
end

def changeset(model, params \\ :invalid) do
model
|> cast(params, [:date])
|> validate_required([:date])
|> validate_current_or_future_date(:date)
end

def validate_current_or_future_date(%{changes: changes}=changeset, field) do
if date = changes[field] do
do_validate_current_or_future_date(changeset, field, date)
else
changeset
end
end

defp do_validate_current_or_future_date(changeset, field, date) do
today = Ecto.Date.utc
if Ecto.Date.compare(date, today) == :lt do
changeset
|> add_error(field, "Date in the past")
else
changeset
end
end
end

Hope that helps.

Andrew
> --
> You received this message because you are subscribed to the Google Groups "elixir-ecto" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to elixir-ecto...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-ecto/4bc017e9-343d-4102-ad2f-967f7314e180%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

germain baptiste delpy

unread,
Jul 23, 2016, 8:12:43 PM7/23/16
to elixir-ecto
It's helpful ~
Tks, G.
Reply all
Reply to author
Forward
0 new messages