How can I specify the format of a certain parameters in a URL? For example, for this URL: my_website.com/users/123 I want the user_id parameter in the URL to be integer and positive.
How can I do that? Is it done via web/routes.ex via regular expressions?
This is not possible in the Router in Phoenix because of the way the Router is implemented -- it can only match a path segment (text between /) with an exact constant string, a string with a constant prefix, or any string. You can check it manually in the controller action like this:
def show(conn, %{"user_id" => user_id}) do
case Integer.parse(user_id) do
{user_id, ""} when user_id > 0 ->
# user_id is valid positive integer
text(conn, "ok")
_ ->
# user_id was either not an integer or a negative integer
text(conn, "not ok")
end
end
This is usually being done with Plugs. According to the documentation:
Module plugs are another type of
Plugthat let us define a connection transformation in a module. The module only needs to implement two functions:
init/1which initializes any arguments or options to be passed to call/2call/2which carries out the connection transformation. call/2 is just a function plug that we saw earlier
defmodule HelloPhoenix.Plugs.Checker do
import Plug.Conn
@validator ~r|\A\d+\z|
def init(default), do: default
def call(%Plug.Conn{params: %{"user_id" => user_id}} = conn, _default) do
# ⇓ HERE
unless Regex.match(@validator, user_id), do: raise
assign(conn, :user_id, user_id)
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With