Validate valid URL in Elixir.

Sergio Tapia
sergiotapia
Published in
1 min readSep 18, 2017

Here’s a quick snippet for you guys. Sometimes you need to know if a URL is valid or not.

A simple way to do this is by using the URI.parse/1 function.

defmodule MyApp.Helpers.UrlValidator do
def valid_url(url) do
case URI.parse(url) do
%URI{scheme: nil} -> {:error, "No scheme"}
%URI{host: nil} -> {:error, "No host"}
_ -> {:ok, url}
end
end
end

To call it just do this:

MyApp.Helpers.UrlValidator.valid_url("https://google.com")

It’ll return either {:ok, "https://google.com"} or {:error, error_string} .

Hope this helps!

--

--