本文介绍了如何在Phoenix框架中为必填字段添加自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何更改必填字段的错误消息?如果我有这样的东西
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" ?
推荐答案
"can't be blank"
错误消息目前已硬编码到Ecto中.但是,您可以通过执行以下操作来替换此错误消息:
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
希望有帮助!
这篇关于如何在Phoenix框架中为必填字段添加自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!