Avex.Model
Summary↑
| update(field, functions) | Register a function to update the field |
| update(field, scope, list3) | Defines and register an update function |
| validate(field, functions) | Register a function to validate the field |
| validate(field, scope, list3) | Defines and register a new validation function |
| validate_presence_of(fields, opts \\ []) | Mark the provided fields as required |
Macros
Register a function to update the field
The function must be in the module’s context
All update functions are executed before the validations
Examples
update :field, capitalize
def capitalize(value) when is_binary(value) do
String.capitalize
end
def capitalize(nil), do: nil
Defines and register an update function
Examples
update :field, value do
case Integer.parse(value) do
{i, _} -> i
:error -> nil
end
end
Guards are also supported
update :field, value when is_binary(value) do
case Integer.parse(value) do
{i, _} -> i
:error -> nil
end
end
update :field, value when is_integer(value), do: value
update :field, _, do: nil
Register a function to validate the field
The function can be any of the pre-defined functions or a validation function at the module context.
Examples
validate :field, present(message: "required")
validate :field, my_validation(message: "hey you")
def my_validation(value, opts \ []) do
if value do
{true, value}
else
{false, Keyword.get(opts, :message) || "my message"}
end
end
Defines and register a new validation function
Examples
validate :field, value do
{true, value}
end
Guards are also supported
validate :field, value when is_binary(value) do
{true, value}
end
validate :field, _, do: {false, "invalid"}
Mark the provided fields as required
It is also possible to specify a :message to be returned
for every invalid field
Example
validate_presence_of([:title, :body], message: "required")