View Source EctoCommons.URLValidator (Ecto Commons v0.3.6)

This validator is used to validate URLs.

Options

There are some available :checks depending on the strictness of what you want to validate:

  • :parsable: Checks to see if the URL is parsable by :http_uri.parse/1 Erlang function. This can have issues with international URLs where it should be disabled (see tests). Defaults to enabled
  • :empty: Checks to see if the parsed %URI{} struct is not empty (all fields set to nil). Defaults to enabled
  • :scheme: Checks to see if the parsed %URI{} struct contains a :scheme. Defaults to enabled
  • :host: Checks to see if the parsed %URI{} struct contains a :host. Defaults to enabled
  • :valid_host: Does a :inet.getbyhostname/1 call to check if the host exists. This will do a network call. Defaults to disabled
  • :path: Checks to see if the parsed %URI{} struct contains a :path. Defaults to disabled
  • :http_regexp: Tries to match URL to a regexp known to catch many unwanted URLs (see code). It only accepts HTTP(S) and FTP schemes though. Defaults to disabled

The approach is not yet very satisfactory IMHO, if you have suggestions, Pull Requests are welcome :)

Example:

iex> types = %{url: :string}
iex> params = %{url: "https://www.example.com/"}
iex> Ecto.Changeset.cast({%{}, types}, params, Map.keys(types))
...> |> validate_url(:url)
#Ecto.Changeset<action: nil, changes: %{url: "https://www.example.com/"}, errors: [], data: %{}, valid?: true>

iex> types = %{url: :string}
iex> params = %{url: "https://www.example.com/"}
iex> Ecto.Changeset.cast({%{}, types}, params, Map.keys(types))
...> |> validate_url(:url, checks: [:empty, :path, :scheme, :host])
#Ecto.Changeset<action: nil, changes: %{url: "https://www.example.com/"}, errors: [], data: %{}, valid?: true>

iex> types = %{url: :string}
iex> params = %{url: "some@invalid_url"}
iex> Ecto.Changeset.cast({%{}, types}, params, Map.keys(types))
...> |> validate_url(:url)
#Ecto.Changeset<action: nil, changes: %{url: "some@invalid_url"}, errors: [url: {"is not a valid url", [validation: :url]}], data: %{}, valid?: false>

iex> types = %{url: :string}
iex> params = %{url: "Just some random text"}
iex> Ecto.Changeset.cast({%{}, types}, params, Map.keys(types))
...> |> validate_url(:url)
#Ecto.Changeset<action: nil, changes: %{url: "Just some random text"}, errors: [url: {"is not a valid url", [validation: :url]}], data: %{}, valid?: false>

Summary

Functions

Link to this function

validate_url(changeset, field, opts \\ [])

View Source