Zac
Zac

Reputation: 481

Is it possible to use Elixir changesets/validations without using models?

Would this be as simple as defining your schema and def changeset and never writing any Repo.insert(changeset)?

Upvotes: 4

Views: 3399

Answers (4)

nico
nico

Reputation: 143

Ecto has embedded_schema which allows you to define a schema and use changesets without defining a source. See here for more info.

Upvotes: 2

anthonator
anthonator

Reputation: 5181

There's an Ecto.Changeset like validation library called Justify. It allows you to validate against plain maps and structs. No schemas or types necessary.

https://github.com/sticksnleaves/justify

You can do stuff like:

import Justify

dataset =
  %{email: "[email protected]"}
  |> validate_required(:email)
  |> validate_format(:email, ~r/\A\S@\S\z/)

dataset.valid? == true

Disclaimer: I made Justify

Upvotes: 2

BurmajaM
BurmajaM

Reputation: 724

It is possible and I find it as perfect way to validate API requests.

You can define your model without backend as:

defmodule MyApp.Models.File do
  schema "" do
    field :description, :string, virtual: true
    field :url,         :string, virtual: true
    field :file_name,   :string, virtual: true
    field :ext,         :string, virtual: true
    field :mime,        :string, virtual: true
    field :size,        :integer, virtual: true
  end

  def new_file_cs(model, params) do
    model
    |> cast(params, ~w(url file_name ext mime size), ~w(description))
  end
end

and then somewhere call it as:

def handle_request(data) do
  changeset = File.new_file_cs(%File{}, data)
  case changeset.valid? do
    true  -> :ok
    false -> {:error, changeset}
  end
end

Such error response can be used with ChangesetView generated by phoenix to return uniform error response.

To summarize, your model should have empty schema "" and all fields should be virtual: true

Upvotes: 5

Zac
Zac

Reputation: 481

I hadn't looked at later docs: You can use changesets without defining schemas https://hexdocs.pm/ecto/2.1.0-rc.4/Ecto.Changeset.html#module-schemaless-changesets

Upvotes: 0

Related Questions