Phoenix framework - Custom changeset validations

前端 未结 1 1243
猫巷女王i
猫巷女王i 2021-02-19 16:21

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.

相关标签:
1条回答
  • 2021-02-19 16:24

    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.

    0 讨论(0)
提交回复
热议问题