转换和验证 Ecto 自定义类型
Casting and validating Ecto custom type
我正在为颜色编写自定义 Ecto.Type
(序列化并解析为 CSS 颜色)。
该行为指定 cast/1
回调应该 return :error
除非成功。它不允许 returning 错误原因,并且在与变更集一起使用时会生成通用的 "is invalid" 错误描述。
在无效(不可转换)输入的变更集中允许更好的错误消息的最佳方法是什么?我想创建一个用于变更集的 validate_color
函数,但如果转换失败,该字段将已经有一般错误。
从 Ecto v3.0.0 开始,这是可能的:
When returning {:error, keyword()}
, the returned keyword list will be preserved in the changeset errors, similar to Changeset.add_error/4
. Passing a :message
key, will override the default message.
我正在为颜色编写自定义 Ecto.Type
(序列化并解析为 CSS 颜色)。
该行为指定 cast/1
回调应该 return :error
除非成功。它不允许 returning 错误原因,并且在与变更集一起使用时会生成通用的 "is invalid" 错误描述。
在无效(不可转换)输入的变更集中允许更好的错误消息的最佳方法是什么?我想创建一个用于变更集的 validate_color
函数,但如果转换失败,该字段将已经有一般错误。
从 Ecto v3.0.0 开始,这是可能的:
When returning
{:error, keyword()}
, the returned keyword list will be preserved in the changeset errors, similar toChangeset.add_error/4
. Passing a:message
key, will override the default message.