jpcaruana

jpcaruana

How to do a series of validations in Elixir the most idiomatic way

I am new (but curious) to Elixir. I want to validate two aspects of an URL :

  • it should not be an IP adress
  • the path should not contains /../

I have a function:

def validate_url(url) do
  URI.parse(url)
  |> validate_profile
end

After some pattern matching (to exclude other cases), I come to 2 (unstatisfying) solutions :

1st :

defp validate_profile(%URI{scheme: "https", path: path, host: host, userinfo: nil, fragment: nil}),
     do: validate_path(path)
         |> validate_host(host)
<snip code>
defp validate_profile(_), do: :invalid

defp validate_path(path) do
  case String.split(path, ["/../"]) do
    [_ | []] -> :valid
    _ -> :invalid
  end
end

defp validate_host(:invalid, _), do: :invalid
defp validate_host(:valid, host) do
  case :inet.parse_address(to_charlist(host)) do
    {:ok, _} -> :invalid
    _ -> :valid
  end
end

2nd:

defp validate_profile(%URI{scheme: "https", path: path, host: host, userinfo: nil, fragment: nil}),
     do: validate_path(path, host)
         |> validate_host
<snip code>
defp validate_profile(_), do: :invalid

defp validate_path(path, host) do
  case String.split(path, ["/../"]) do
    [_ | []] -> host
    _ -> :invalid
  end
end

defp validate_host(:invalid), do: :invalid
defp validate_host(host) do
  case :inet.parse_address(to_charlist(host)) do
    {:ok, _} -> :invalid
    _ -> :valid
  end
end

How can I improve here ? Is there a more idiomatic way of doing this ?

Marked As Solved

darkbaby123

darkbaby123

Below is an example to use with. Each validation step only return ok/error tuple. The url is not changed so it can be reused in each step.

@spec validate_url(raw_url :: URI.t() | binary) :: {:ok, URI.t()} | :error
def validate_url(raw_url) do
  with url <- URI.parse(raw_url),
       :ok <- validate_path(url),
       :ok <- validate_host(url) do
    {:ok, url}
  else
    :error -> :error
  end
end

@spec validate_path(URI.t()) :: :ok | :error
defp validate_path(%URI{path: path}) do
  # ...
end

@spec validate_host(URI.t()) :: :ok | :error
defp validate_host(%URI{host: host}) do
  # ...
end

Pipeline is suitable when you have a data structure to express both url and validation result. The simplest data structure is {:ok, url} | :error .

Also Liked

dimitarvp

dimitarvp

This could be a good candidate for using the with keyword.

wanton7

wanton7

I’m no Elixir guru but probably something like this

def parse_url(url) do
  {:ok, URI.parse(url)}
  |> validate_profile()
  |> validate_stuff()
end

defp validate_profile({:ok, url} = data) do
# validate here
# if ok
data
# if error
{:error, "profile validation failed"}
end

defp validate_stuff({:ok, url} = data) do
# validate here
# if ok
data
# if error
{:error, "stuff validation failed"}
end

defp validate_stuff(x), do: x

In case you need to return nil or string if it’s valid use something like

def parse_url(url) do
  {:ok, URI.parse(url)}
  |> validate_profile()
  |> validate_stuff()
  |> case do
    {:ok, url} -> url
    _ -> nil
  end
end
NobbZ

NobbZ

Why?

I can understand why you do not want the server part to be an IP. But why restricting the path to not contain /../?

http://example.com/path/../foo and http://example.com/foo are different URLs. Not every server will interprete .. as “one folder up”.

jpcaruana

jpcaruana

that’s in the protocol I want to implement (and I am not implementing a web server)

Where Next?

Popular in Questions Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New

We're in Beta

About us Mission Statement