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

你说的曾经没有我的故事 提交于 2020-01-13 10:12:09

问题


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" ?


回答1:


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!




回答2:


I normally customize this way:

validate_required(changeset, [:email], message: "Email cannot be blank.")



回答3:


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


来源:https://stackoverflow.com/questions/32032246/how-to-add-a-custom-error-message-for-a-required-field-in-phoenix-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!