diff --git a/lib/useful.ex b/lib/useful.ex index 258a467..5258489 100644 --- a/lib/useful.ex +++ b/lib/useful.ex @@ -214,6 +214,17 @@ defmodule Useful do "#{key}: #{value}" end + @doc """ + `is_valid_url?/1` checks if a string is a valid URL. + A valid URL starts with a `scheme` (e.g. `http://` or `https://`), + so strings that start with "www" are considered invalid. + """ + def is_valid_url?(string) do + [:scheme, :host, :port] + |> Enum.map(&Map.get(URI.parse(string), &1)) + |> Enum.all?() + end + # Recap: https://elixir-lang.org/getting-started/basic-types.html#tuples defp to_list_of_tuples(map) do map diff --git a/test/useful_test.exs b/test/useful_test.exs index 48f0865..288fafd 100644 --- a/test/useful_test.exs +++ b/test/useful_test.exs @@ -330,4 +330,17 @@ defmodule UsefulTest do assert Useful.typeof(tuple) == "tuple" end end + + describe "is_valid_url?/1" do + test "are URL valid" do + assert Useful.is_valid_url?("http://www.google.com") == true + assert Useful.is_valid_url?("http//google.com") == false + assert Useful.is_valid_url?("ftp://google.com") == true + assert Useful.is_valid_url?("https://google.com/api&url=ok") == true + assert Useful.is_valid_url?("http://localhost:3000") == true + assert Useful.is_valid_url?("https://localhost") == true + assert Useful.is_valid_url?("htt:/google") == false + assert Useful.is_valid_url?("www.google.com") == false + end + end end