UrlValidator

An Ecto changeset validator for HTTP and HTTPS URLs.

Installation

If available in Hex, the package can be installed by adding url_validator to your list of dependencies in mix.exs:

def deps do
[
{:url_validator, "~> 0.1.0"}
]
end

Usage

Call UrlValidator.validate_url/3 with an Ecto changeset and the field to validate. The validator accepts URLs with an http or https scheme and a host.

def changeset(user, attrs) do
user
|> Ecto.Changeset.cast(attrs, [:website])
|> UrlValidator.validate_url(:website)
end

By default, the field is required and invalid values produce the error "Invalid URL". Use optional: true to allow an empty value, or customize the validation error with the message option:

changeset
|> UrlValidator.validate_url(:website, optional: true)
changeset
|> UrlValidator.validate_url(:website, message: "must be a valid URL")

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/url_validator.