Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PR] Add is_valid_url? function #68

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions lib/useful.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions test/useful_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading