defmodule MyApp.Validations.Email do
use Ash.Resource.Validation
@impl true
def init(opts) do
{:ok, opts}
end
@impl true
def supports(_opts), do: [Ash.Changeset, Ash.Query]
@impl true
def validate(subject, opts, _context) do
value = get_value(subject, opts[:attribute])
if is_nil(value) || valid_email?(value) do
:ok
else
{:error, field: opts[:attribute], message: "must be a valid email"}
end
end
defp get_value(%Ash.Changeset{} = changeset, attribute) do
Ash.Changeset.get_argument_or_attribute(changeset, attribute)
end
defp get_value(%Ash.Query{} = query, attribute) do
Ash.Query.get_argument(query, attribute)
end
defp valid_email?(email) do
String.match?(email, ~r/^[^\s]+@[^\s]+\.[^\s]+$/)
end
end
defmodule MyApp.Validations.Email do
use Ash.Resource.Validation
@impl true
def init(opts) do
{:ok, opts}
end
@impl true
def supports(_opts), do: [Ash.Changeset, Ash.Query]
@impl true
def validate(subject, opts, _context) do
value = get_value(subject, opts[:attribute])
if is_nil(value) || valid_email?(value) do
:ok
else
{:error, field: opts[:attribute], message: "must be a valid email"}
end
end
defp get_value(%Ash.Changeset{} = changeset, attribute) do
Ash.Changeset.get_argument_or_attribute(changeset, attribute)
end
defp get_value(%Ash.Query{} = query, attribute) do
Ash.Query.get_argument(query, attribute)
end
defp valid_email?(email) do
String.match?(email, ~r/^[^\s]+@[^\s]+\.[^\s]+$/)
end
end