Utility.Validators behaviour (Portico/Z v0.1.0)
Behaviour and helper functions for validating values.
NOTE: Functions in this module get auto-imported into any ZSchemas
module.
Validator Behaviour
The "validator" behaviour specifies a method by which any kind of data can be validated and returned in a consistent format. This is handy because it allows us to define modules that perform different kinds of validations, but to use them all in the same way, eg. in Ecto
changesets.
Validators NOT to Implement
Don't implement an email validator. There are a few reasons, but our top two are:
- It's basically impossible
- Browsers already have an email validator!
Instead of validating in the back-end, just use Phoenix.HTML.Form.email_input/3
, which will have the browser validate the email input before the form even gets submitted!
Link to this section Summary
Functions
Use any module implementing the Elixir.Utility.Validators
behaviour as a validator for Ecto.Changeset.validate_change/3
.
Link to this section Functions
validate_change_with(changeset, field, validator, args \\ [])
Use any module implementing the Elixir.Utility.Validators
behaviour as a validator for Ecto.Changeset.validate_change/3
.
Typical Usage
Typically, this function would be used in an Ecto Changeset pipeline. For example:
model
|> cast(attrs, [:url, :other_field])
|> validate_required([:url, :other_field])
|> validate_change_with(:url, Utility.Validators.UrlValidator)
args
get passed to the validator module for use in validation, if
necessary.
See Utility.Validators.UrlValidator
for an example module implementing this behaviour.