Conditional Validation in Ecto for OR - 1 of 2 fields is required

前端 未结 3 1441
时光取名叫无心
时光取名叫无心 2021-02-14 02:24

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.

So, for example, if I want to check t

3条回答
  •  孤城傲影
    2021-02-14 03:02

    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)"
      )
    )
    

    And use check_constraint to validate the changeset:

    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
    

提交回复
热议问题