wintermeyer

wintermeyer

How can I do a custom validation in the following resource to make sure that the attribute use_by_date is today or later but not in the past?

defmodule App.Shop.Product do
  use Ash.Resource, data_layer: Ash.DataLayer.Ets

  attributes do
    uuid_primary_key :id

    attribute :name, :string do
      allow_nil? false
      constraints min_length: 3
    end

    attribute :price, :decimal

    attribute :use_by_date, :date do
      allow_nil? false
    end
  end

  actions do
    defaults [:create, :read]
  end
end

Showing Posts 1 to 4

zachdaniel

zachdaniel

Creator of Ash

What you’re looking for is validations. I don’t think our built in validations will do datetime comparisons, but you can do it with a custom validation.

validate {MyApp.Validations.InTheFuture, field: :use_by_date} 
defmodule MyApp.Validations.InTheFuture do
  use Ash.Resource.Validation
  
  def validate(changeset, opts) do
    case Ash.Changeset.fetch_argument_or_change(changeset, opts[:field]) do
      :error ->
         # in this case, they aren't changing the field, or providing an argument by the same name
         :ok

      {:ok, value} ->
        if DateTime.after?(DateTime.utc_now(), value) do
          :ok
        else
           {:error, field: opts[:field], message: "must be in the future"}
        end
    end
  end
end

EDIT: The validations guide is here: Validations — ash v3.29.3

wintermeyer

wintermeyer OP

For the archive and Google: The code in the resource would look like this.

  attributes do
    # [...]

    attribute :use_by_date, :date do
      allow_nil? false
    end
  end

  validations do
    validate {App.Validations.InTheFuture, field: :use_by_date}
  end
sheerlox

sheerlox

I had to tackle the same issue today and adapted the code from Ash’s compare() validation to work with Date structs. It has the same behavior, only the accepted argument types changed.

I’m posting it for the record, also it can be easily adapted to work with DateTime instead.


@zachdaniel I was wondering if maybe it would be interesting to cast to the expected data types before running the validations because I think that would allow the built-in compare validation to work with Date and DateTime? I’m not sure what that could imply, so I’m bringing up the idea in case it’s a good one :smile:

EDIT: my bad, seems like the attribute is already cast in the validator. Not sure why using the classic validation with Date.utc_now() wasn’t working then :sweat_smile:

EDIT 2:

# not working (no error added to changeset)
validate compare(:position_end_date, greater_than: Date.utc_today()),
  where: present(:position_end_date),
  message: "cannot be in the past"

# working perfectly
validate {TalentIdeal.Shared.Validators.DateCompare,
          attribute: :position_end_date, greater_than: Date.utc_today()},
          where: present(:position_end_date),
          message: "cannot be in the past"

Comp should support the Date struct so not sure what the issue might be when using the built-in compare, looks like it should work.

Anyway nothing urgent, 3.0 is a much more serious topic :grin:

zachdaniel

zachdaniel

Creator of Ash

So, not sure why the builtin one wouldn’t be working, but you need to be careful with Date.utc_today() like that. That will be referring to the day your app was compiled :slight_smile:

Make sure to use &Date.utc_today/0

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews