Phoenix Framework: Validate route parameter in the router

Turns out that I was wrong when said this… I just followed their docs to the letter, and the code was not compiling, but after a night of sleep I realized how to do it:

defmodule TasksWeb.Router do
  use TasksWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    #plug :fetch_flash
    plug :fetch_live_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug :put_root_layout, {TasksWeb.LayoutView, :root}

    # *** NEW CODE TO ENABLE THE PLUG VALIDATOR CHECK ***
    plug Plug.Validator, on_error: &TasksWeb.Router.validation_error_callback/2
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", TasksWeb do
    pipe_through :browser
    get "/", PageController, :index

    live "/todos", TodoLive

    # *** NEW CODE TO ENABLE THE PLUG VALIDATOR CHECK ***
    live "/todos/:date", TodoLive, private: %{validate: %{date: &Utils.Validators.Date.valid_iso8601?/1}}
  end

  # *** CALLBACK TO HANDLE THE ERRORS RETURNED BY THE PLUG VALIDATOR CHECK ***
  def validation_error_callback(conn, _errors) do
    conn
    |> put_status(:not_found)
    |> put_view(TasksWeb.ErrorView)
    |> render("404.html")
    |> halt()
  end

  # Other scopes may use custom stacks.
  # scope "/api", TasksWeb do
  #   pipe_through :api
  # end
end

4 Likes