【发布时间】:2022-03-27 16:00:43
【问题描述】:
Ecto 可以验证格式、包含、唯一性等,但我看不到如何验证存在?如果字段为空,是否有向字段添加错误的方法?就像 RoR 中的 validates_presence_of 一样?我可以手动制作,这不是问题,但我想知道是否已经存在类似validate_presence\3 之类的方法?
【问题讨论】:
Ecto 可以验证格式、包含、唯一性等,但我看不到如何验证存在?如果字段为空,是否有向字段添加错误的方法?就像 RoR 中的 validates_presence_of 一样?我可以手动制作,这不是问题,但我想知道是否已经存在类似validate_presence\3 之类的方法?
【问题讨论】:
只需在模型中使用 required_fields 注释器。
@required_fields ~w(name email)
对于一个共有 4 个字段和 2 个必填字段的客户模型,如下所示:
defmodule HelloPhoenix.Customer do
use HelloPhoenix.Web, :model
schema "customers" do
field :name, :string
field :email, :string
field :bio, :string
field :number_of_pets, :integer
timestamps
end
@required_fields ~w(name email)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
Phoenix 将自动验证是否存在必填字段,并在表单顶部显示错误消息,如下所示:
【讨论】:
validate_required/3我不能说它在 2015 年的情况如何,但现在有一段时间了,validate_required/3 functoin 相当于 Rails 中的“存在”验证。这个函数:
验证变更集中是否存在一个或多个字段 [...]
【讨论】: