如何验证 Phoenix 框架中的存在?
How to validate presence in Phoenix framework?
Ecto 可以验证格式、包含、唯一性等,但我看不出如何验证存在?如果字段为空,是否有方法向字段添加错误?就像 RoR 中的 validates_presence_of
一样?我可以手动制作它,这不是问题,但我想知道是否已经存在像 validate_presence
之类的方法?
只需在模型中使用 required_fields 注释器即可。
@required_fields ~w(name email)
对于总共有 4 个字段和 2 个必填字段的 Customer 模型,如下所示:
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 函数已经有一段时间了,它相当于 Rails 中的“存在”验证。这个函数:
Validates that one or more fields are present in the changeset [...]
Ecto 可以验证格式、包含、唯一性等,但我看不出如何验证存在?如果字段为空,是否有方法向字段添加错误?就像 RoR 中的 validates_presence_of
一样?我可以手动制作它,这不是问题,但我想知道是否已经存在像 validate_presence
之类的方法?
只需在模型中使用 required_fields 注释器即可。
@required_fields ~w(name email)
对于总共有 4 个字段和 2 个必填字段的 Customer 模型,如下所示:
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 函数已经有一段时间了,它相当于 Rails 中的“存在”验证。这个函数:
Validates that one or more fields are present in the changeset [...]