Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix framework - Custom changeset validations

Tags:

ecto

I'm really new to phoenix and elixir, so my apologies if these seem like simple questions. I've searched stack overflow and blogs before I thought about posting it here.

I've got 2 fields in a model, field A : integer and field B : integer. When doing my validations with my changeset I want to create a custom validation that checks if field A is more than field b when creating a new item, and if so then flash a error message and bring them back to the :new route. Sorry if I'm not using the right terminologies.

So I guess this now becomes a 2 part question. First, should I even be doing this in my model by creating a custom validation or should this be in the controller? And second, what is the simplest way to write this in phoenix?

Thanks once again.

like image 758
user5895709 Avatar asked Feb 07 '16 18:02

user5895709


1 Answers

I had to do this exact thing and it took me a bit of time to figure it out. I ended writing a custom validator for the changeset.

def changeset(model, params \\ :empty) do
  model
  |> cast(params, @required_fields, @optional_fields)
  |> validate_a_less_eq_b
end

defp validate_a_less_eq_b(changeset) do
  a = get_field(changeset, :a)
  b = get_field(changeset, :b)

  validate_a_less_eq_b(changeset, a, b)
end
defp validate_a_less_eq_b(changeset, a, b) when a > b do
  add_error(changeset, :max, "'A' cannot be more than 'B'")
end
defp validate_a_less_eq_b(changeset, _, _), do: changeset

You would, of course, want to use regular validators to ensure that a and b are valid numbers.

like image 122
jthopple Avatar answered Sep 28 '22 09:09

jthopple