Search code examples
elixir

How to validate url in elixir?


I want to validate uris like:

http://vk.com
http://semantic-ui.com/collections/menu.html
https://translate.yandex.ru/?text=poll&lang=en-ru

and not

www.vk.com
abdeeej
http://vk

but haven't found either package of native code implementation for it.

How can I do that?


Solution

  • All of those are technically valid URLs according to the spec so URI.parse/1 returns a %URI{} struct for all, but if you want to reject domains without a scheme and a dot in the host, you can do:

    valid? = fn url ->
      uri = URI.parse(url)
      uri.scheme != nil && uri.host =~ "."
    end
    

    Test:

    urls = [
      "http://vk.com",
      "http://semantic-ui.com/collections/menu.html",
      "https://translate.yandex.ru/?text=poll&lang=en-ru",
      "www.vk.com",
      "abdeeej",
      "http://vk"
    ]
    
    urls |> Enum.map(valid?) |> IO.inspect
    

    Output:

    [true, true, true, false, false, false]