在Ecto中针对OR进行条件验证-需要2个字段中的1个 [英] Conditional Validation in Ecto for OR - 1 of 2 fields is required
问题描述
我该如何对OR逻辑进行条件验证,我们将检查是否存在2个值中的1个或同时存在两个值。
How can I do conditional validation for OR logic, where we check to see if 1 of the 2 values is present or both values are present.
因此,对于例如,如果我要检查以确保填写电子邮件
或移动电话
字段...我想要才能将列表传递到 validate_required_inclusion
的个字段
中,以验证列表中至少一个字段是不为空。
So, for example, if I want to check to make sure that the email
or the mobile
fields are filled... I want to be able to pass a list into fields
of validate_required_inclusion
to validate that at least 1 of the fields in the list is not null.
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:email, :first_name, :last_name, :password_hash, :role, :birthdate, :address1, :address2, :city, :state, :zip, :status, :mobile, :card, :sms_code, :status])
|> validate_required_inclusion([:email , :mobile])
end
def validate_required_inclusion(changeset, fields, options \\ []) do
end
我该如何进行条件或验证?
How can I do this conditional OR validation?
推荐答案
您还可以在数据库中创建约束,例如通过编写迁移:
You could also create the constraint in the database, e.g. by writing a migration:
create(
constraint(
:users,
:email_or_mobile,
check: "(email IS NOT NULL) OR (mobile IS NOT NULL)"
)
)
并使用 check_constraint
来验证变更集:
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:email, :first_name, :last_name, :password_hash, :role, :birthdate, :address1, :address2, :city, :state, :zip, :status, :mobile, :card, :sms_code, :status])
|> check_constraint(
:users_table,
name: :email_or_mobile,
message: dgettext("errors", "can't be blank")
)
end
这篇关于在Ecto中针对OR进行条件验证-需要2个字段中的1个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!