From 93b6596476054fd261c5ec99a3eeb57556a5093b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lui=CC=81s=20Arteiro?= Date: Fri, 10 Nov 2023 19:31:19 +0000 Subject: [PATCH 1/3] feat: Add `is_valid_url?` function. #64 --- lib/useful.ex | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/useful.ex b/lib/useful.ex index 258a467..8601158 100644 --- a/lib/useful.ex +++ b/lib/useful.ex @@ -214,6 +214,15 @@ defmodule Useful do "#{key}: #{value}" end + @doc """ + `is_valid_url?/1` checks if a string is a valid URL. + """ + 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 From 4897c1ef5c5475e77b191b9ffce8ffbada15e1b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lui=CC=81s=20Arteiro?= Date: Sat, 11 Nov 2023 15:41:28 +0000 Subject: [PATCH 2/3] chore: Adding tests. #64 --- test/useful_test.exs | 13 +++++++++++++ 1 file changed, 13 insertions(+) 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 From f329075368e6a6ba1a6fc22ea59c4306de993e9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lui=CC=81s=20Arteiro?= Date: Sun, 12 Nov 2023 17:40:23 +0000 Subject: [PATCH 3/3] chore: Finishing comment. #64 --- lib/useful.ex | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/useful.ex b/lib/useful.ex index 8601158..5258489 100644 --- a/lib/useful.ex +++ b/lib/useful.ex @@ -216,6 +216,8 @@ defmodule Useful do @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]