View Source ExToolkit.Ecto.Changeset (ExToolkit v0.9.13)
Helper functions that extend Ecto.Changeset
functionality.
Summary
Functions
Validates the structure of a URL field in an Ecto changeset. It does not make it required field.
Functions
Validates the structure of a URL field in an Ecto changeset. It does not make it required field.
If the field
in the changeset
is a URL, this function ensures that it has a scheme (defaulting to "https://" if
none is present), and then checks the URL's structure against a regular expression.
If the URL's structure is invalid, the error_message
is attached to the field
in the changeset
's errors.
Parameters
changeset
: The Ecto changeset containing the URL to validate.field
: The key (atom) for the field in the changeset containing the URL.error_message
: The error message to attach to thefield
in thechangeset
if the URL is invalid.
Examples
iex> types = %{url: :string}
iex> params = %{url: "https://www.example.com/"}
iex> Ecto.Changeset.cast({%{}, types}, params, Map.keys(types))
...> |> validate_url(:url, "is not a valid url")
#Ecto.Changeset<action: nil, changes: %{url: "https://www.example.com/"}, errors: [], data: %{}, valid?: true, ...>
iex> types = %{url: :string}
iex> params = %{url: "www.example.com/"}
iex> Ecto.Changeset.cast({%{}, types}, params, Map.keys(types))
...> |> validate_url(:url, "is not a valid url")
#Ecto.Changeset<action: nil, changes: %{url: "https://www.example.com/"}, errors: [], data: %{}, valid?: true, ...>
iex> types = %{url: :string}
iex> params = %{url: nil}
iex> Ecto.Changeset.cast({%{}, types}, params, Map.keys(types))
...> |> validate_url(:url, "is not a valid url")
#Ecto.Changeset<action: nil, changes: %{}, 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, "is not a valid url")
#Ecto.Changeset<action: nil, changes: %{url: "https://some@invalid_url"}, errors: [url: {"is not a valid url", [validation: :format]}], 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, "is not a valid url")
#Ecto.Changeset<action: nil, changes: %{url: "https://Just some random text"}, errors: [url: {"is not a valid url", [validation: :format]}], data: %{}, valid?: false, ...>