Created
December 15, 2022 01:19
-
-
Save dmkit/accbb979e0c1c01d642c649331f73646 to your computer and use it in GitHub Desktop.
[Elixir][Ecto] trim input fields / remove trailing and leading whitespaces with Ecto changeset (User.trim/2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule User do | |
use Ecto.Schema | |
import Ecto.Changeset | |
alias Ecto.Changeset | |
schema "users" do | |
field :name | |
field :email | |
field :age, :integer | |
field :about | |
end | |
def changeset(user, params \\ %{}) do | |
user | |
|> cast(params, [:name, :email, :age, :about]) | |
|> trim([:name, :email, :about]) | |
|> validate_required([:name, :email]) | |
end | |
def trim(%Changeset{changes: changes} = changeset, fields) when is_list(fields) do | |
changes = | |
List.foldl(fields, changes, fn field, changes -> | |
value = Map.get(changes, field) | |
if is_nil(value), do: changes, else: Map.put(changes, field, String.trim(value)) | |
end) | |
%{changeset | changes: changes} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment