Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom error message for a required field in Phoenix framework

How can I change the error message for required fields? If I have something like that

@required_fields ~w(name email)

and I want to show "no way it's empty" instead of the default value of "can't be blank" ?

like image 661
NoDisplayName Avatar asked Aug 16 '15 05:08

NoDisplayName


3 Answers

I normally customize this way:

validate_required(changeset, [:email], message: "Email cannot be blank.")
like image 135
Cristiano Carvalho Avatar answered Oct 05 '22 00:10

Cristiano Carvalho


The "can't be blank" error message is hardcoded into Ecto at the moment. However, you can replace this error message by doing:

def changeset(model, params \\ :empty) do
  model
  |> cast(params, @required_fields, @optional_fields)
  |> required_error_messages("no way it's empty")
end

def required_error_messages(changeset, new_error_message) do
  update_in changeset.errors, &Enum.map(&1, fn
    {key, "can't be blank"} -> {key, new_error_message}
    {_key, _error} = tuple  -> tuple
  end)
end

Hope that helps!

like image 31
Gjaldon Avatar answered Oct 05 '22 01:10

Gjaldon


I think Ecto.Changeset may have changed since the last answer was posted. As of ecto_sql 3.1, the %Ecto.Changeset{} struct stores errors like this:

errors: [address1: {"can't be blank", [validation: :required]}]

So I had to alter the structure of the previous solution a bit. In this example, I am using cast/4 to cast a raw map (the first argument may be a changeset or a data tuple as {data, types}):

@permitted [:name, :phone, :url]
@parameter_types %{name: :string, phone: :string, url: :string}

def signup_changeset(params) do
    IO.inspect params
    cast({%{}, @parameter_types}, params, @permitted)
    |> validate_required([:name, :phone, :url])
    |> required_error_messages("no way it's empty")
end

defp required_error_messages(changeset, new_error_message) do
    update_in changeset.errors, &Enum.map(&1, fn
      {key, {"can't be blank", rules}} -> {key, {new_error_message, rules}}
      tuple  -> tuple
    end)
end

Note that you have to call validate_required before you will have any default "can't be blank" strings.

Alternatively, you can verbosely set an error message for each field in violation:

@permitted [:name, :phone, :url]
@parameter_types %{name: :string, phone: :string, url: :string}

def signup_changeset(params) do
    cast({%{}, @parameter_types}, params, @permitted)
    |> validate_required(:name, message: "Dude. You need an address.")
    |> validate_required(:phone, message: "You must have a name.")
    |> validate_required(:url, message: "We need a valid URL for your homepage.")
  end
like image 39
Everett Avatar answered Oct 05 '22 01:10

Everett