Parse and validate parameters

It’s popular to do validate within changeset of Ecto, but I think it’s better to do it before the main logic.
That’s one of the reasons I port grape to elixir world as maru.

I brought Maru’s parameter parser and validation into Pheoenix a few days ago, it could be used as maru, e.g.

defmodule Controller do
  use MyApp.Web, :controller
  use Maru.Parameter.Phoenix

  params do
    requires :age,    type: Integer, values: 18..65
    requires :gender, type: Atom, values: [:male, :female], default: :female
    group    :name,   type: Map do
      requires :first_name
      requires :last_name
    end
    optional :intro,  type: String, regexp: ~r/^[a-z]+$/
    optional :avatar, type: File
    optional :avatar_url, type: String
    exactly_one_of [:avatar, :avatar_url]
  end
  def create(conn, params) do
    ...
  end
end

It’s a simple example, you can find more information here.

Is it useful for phoenix development? And is there any other idea about it?

3 Likes

Great work!

I definitely think it would be useful. However I’ve been using params for my Phoenix app before, and it works nicely. The idea is quite similar, although it leverages Ecto schema and changeset for validation.

(You can already use plain Ecto.Schema and Ecto.Changeset for this, and params makes it easier using defparams just before your route handler.)

1 Like

Thank you!
I find another similar project validation.
I think maru parameter and params focus on different things.
params provide an easier way to build Ecto schema, maru parameter focus on process complex input data.