-
Notifications
You must be signed in to change notification settings - Fork 0
/
changeset.ex
51 lines (42 loc) · 1.52 KB
/
changeset.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
if Code.ensure_loaded?(Ecto) do
defmodule BrDocs.Changeset do
@moduledoc """
BrDocs validations to use with `Ecto.Changeset`
Although `BrDocs` can be used as standalone lib, trying to use `BrDocs.Changeset` without `Ecto` installed will raise an exception.
"""
@doc ~s"""
Validates a changeset against `BrDocs` validation rules. Returns an `Ecto.Changeset`.
Arguments are:
* `field` - is the changeset field to be validated
* `kind` - is the `BrDocs.Doc` document kind which will identify the validation rule. It must be one of #{
BrDocs.Doc.formatted_available_docs()
}.
## Examples
defmodule User do
use Ecto.Schema
use BrDocs.Changeset
import Ecto.Changeset
schema "users" do
field :name
field :brazilian_doc
end
def changeset(user, params \\\\ %{}) do
user
|> cast(params, [:name, :brazilian_doc])
|> validate_required([:name, :brazilian_doc])
|> validate_doc(:brazilian_doc, :cpf)
|> unique_constraint(:brazilian_doc)
end
end
"""
@spec validate_doc(Ecto.Changeset.t(), atom(), atom(), String.t() | nil) :: Ecto.Changeset.t()
def validate_doc(changeset, field, kind, custom_message \\ nil) do
with value <- Ecto.Changeset.get_change(changeset, field, ""),
true <- BrDocs.validate(value, kind) do
changeset
else
_ -> Ecto.Changeset.add_error(changeset, field, custom_message || "is invalid")
end
end
end
end