Where in the pipeline is the right place to silently correct input mistakes

I want to trim blanks from certain inputs. For example, I’d like to silently remove leading and trailing blanks from a new account’s “human name” and “login name”, so as to avoid inserting values like these into the database:

  "auth_id" => "         login id with blanks        ",
  "display_name" => "     Dr. Dawn with leading and trailing blanks        ",
  "email" => "email@email.com",

(It’s nice that email_input strips blanks, though I wonder if I can depend on that, cross-browser.)

I could see using String.trim in the controller, or in a changeset, or possibly elsewhere. Is there a convention for where to do such things?

No standard way as far as I remember. Closest I could think of is controller parameter scrubbing but it’s not what you want.

You should roll your own Plug or check hex.pm if anybody else did it. (I made one in the past but never open-sourced it).

1 Like

I perform validation and cleanup on my internal API bounds, not in controllers or anything like that. :slight_smile:


I ended up creating a custom type that trims strings when they are being cast into a changeset:

defmodule Crit.Ecto.TrimmedString do
  @behaviour Ecto.Type
  def type, do: :string

  def cast(possibly_untrimmed) when is_binary(possibly_untrimmed), 
    do: {:ok, String.trim(possibly_untrimmed)}
  def cast(_), do: :error

  def load(string), do: {:ok, string}
  def dump(string), do: {:ok, string}
  schema "users" do
    field :auth_id, TrimmedString
    field :display_name, TrimmedString
    field :email, TrimmedString
    field :active, :boolean, default: true
    has_one :permission_list, PermissionList