formex_ecto v0.1.9 Formex.Ecto.ChangesetValidator behaviour View Source
Changeset validator adapter for Formex
Why?
Validators was introduced in Formex 0.5, in older versions validation was perfomred via Changesets. So if you already have a project with older Formex, you would have to rewrite all validations. But you can also use this validator instead.
Anyway, you can use any validator with any forms that uses Ecto.
Limitations
- can be used only with Ecto schemas.
length
validation for collections doesn’t work. Maybe there is a way to fix it. If you need this now - use Vex validator instead.
Installation
See Formex.Validator
docs.
Usage
defmodule App.UserType do
use Formex.Type
use Formex.Ecto.Type
use Formex.Ecto.ChangesetValidator # <- add this
Inside the build_form
def build_form(form) do
form
|> add(:username, :text_input, validation: [
:required
])
|> add(:email, :text_input, validation: [
required: [message: "give me your email!"],
format: [arg: ~r/@/]
])
|> add(:age, :text_input, validation: [
:required,
inclusion: [arg: 13..100, message: "you must be 13."]
])
end
Keys from validation
list are converted to validate_
functions from
Ecto.Changeset
. For example required
-> Ecto.Changeset.validate_required/3
.
Value is list of options. If function requires additional argument
(e.g. Ecto.Changeset.validate_format/4
needs format as third argument)
it must be passed as :arg
option.
Outside the build_form
There is changeset_validation/2
callback where is passed changeset struct as argument.
You can use Ecto.Changeset.add_error/4
to add errors to fields that exists in that form.
You cannot alter data from here. This changeset is used only to pass errors. If you want to
modify changeset, use Formex.Ecto.Type.changeset_after_create_callback/2
instead
def build_form(form) do
form
|> add(:username, :text_input)
# ...
end
def changeset_validation(changeset, _form) do
add_error(:username, "error message")
end
Link to this section Summary
Functions
Callback implementation for Formex.Validator.validate/1
Link to this section Functions
Callback implementation for Formex.Validator.validate/1
.
Link to this section Callbacks
changeset_validation(changeset :: Ecto.Changeset.t, form :: Formex.Form.t) :: Formex.Form.t