Skip to content

Instantly share code, notes, and snippets.

@nallwhy
Created January 19, 2024 05:08
Show Gist options
  • Save nallwhy/0ddb3a32f9ccc502ecc06e991ca104a4 to your computer and use it in GitHub Desktop.
Save nallwhy/0ddb3a32f9ccc502ecc06e991ca104a4 to your computer and use it in GitHub Desktop.
IsNil Ash validation (validate the fields are nil)
defmodule MyApp.Validation.IsNil do
use Ash.Resource.Validation
alias Ash.Error.Changes.{NoSuchAttribute, InvalidAttribute}
@impl true
def init(opts) do
{:ok, opts}
end
@impl true
def validate(changeset, opts) do
fields = Keyword.get(opts, :fields)
errors =
fields
|> Enum.reduce([], fn field, errors ->
case changeset.data |> Map.has_key?(field) do
false ->
error =
[resource: changeset.resource, name: field]
|> with_description(opts)
|> NoSuchAttribute.exception()
[error | errors]
true ->
case changeset.data |> Map.get(field) do
nil ->
errors
_ ->
error =
[field: field, value: Ash.Changeset.get_attribute(changeset, field)]
|> with_description(opts)
|> InvalidAttribute.exception()
[error | errors]
end
end
end)
|> Enum.reverse()
case errors do
[] -> :ok
errors -> {:error, errors}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment