Phoenix framework - Custom changeset validations

跟風遠走 提交于 2019-12-21 07:38:08

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/35257104/phoenix-framework-custom-changeset-validations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!