Can i pipe the same function multiple times?

I need to pipe validate_length for multiple fields, but it seems that it doesn’t accept more than one, or that’s at least what I’ve seen in the documentation.

As an example, this is what I would like to do :

def changeset(struct, params \\ %{}) do
  struct
  |> cast(params, @required_fields, @optional_fields)
  |> validate_length(:field_a, max: 80)
  |> validate_length(:field_b, max: 80)
  |> validate_length(:field_c, max: 80).
end

I don’t know if using it multiple times would work, as I haven’t tried yet and It seems repetitive. Is it possible to have it inline? Or should I just try to do it as in the example above?
Would it be better to have a custom method?

1 Like

Calling it multiple times is the way to go. If you find it repetitive, you can easily define a helper for it, for example:

def validate_lengths(changeset, fields, opts) do
  Enum.reduce(fields, changeset, &validate_length(&1, &2, opts))
end
1 Like

Alrighty, thanks for the answer!

Calling multiple times will allow you to have different messages for each :wink:

1 Like

I cannot overstate how useful this is too. :wink:

1 Like