clojuremalli

How do you validate a string representing a local date in malli?


I'm trying to use https://github.com/metosin/malli?tab=readme-ov-file#malliexperimentaltime

Here is what I have

(ns foobar.core
  (:require [malli.core :as m]
            [malli.registry :as mr]
            [malli.experimental.time :as met]))

;; This should add the malli.experimental.time schemas
(mr/set-default-registry!
  (mr/composite-registry
    (m/default-schemas)
    (met/schemas)))

So, I would expect one of those things to be truthy, but none is:

(m/validate :time/local-date "2024-01-01")
(m/validate [:time/local-date] "2024-01-01")
(m/validate [:time/local-date {:pattern "yyyy-mm-dd"}] "2024-01-01")
(m/validate [:time/local-date {:pattern "yyyy-MM-dd"}] "2024-01-01")
(m/validate [:time/local-date {:pattern "YYYY-MM-DD"}] "2024-01-01")

What am I missing here ?

The doc also mentions a "transformation" feature, is that required here ? https://github.com/metosin/malli?tab=readme-ov-file#transformation---malliexperimentaltimetransform


Solution

  • Thanks to @gwang-jim-kim for the help, but I found at what I was missing:

    So, in the end, this does what I want:

    (ns flight.core
      (:require [malli.core :as m]
                [malli.registry :as mr]
                [malli.experimental.time :as met]
                [malli.experimental.time.transform :as mett]))
    
    (mr/set-default-registry!
      (mr/composite-registry
        (m/default-schemas)
        (met/schemas)))
    
    (def schema [:time/local-date {:pattern "yyyy-MM-dd"}] )
    
    (m/validate schema "2024-01-01") ;;=> false, the string is not a LocalDate 
    
    (m/coerce schema "2024-01-01" mett/time-transformer) ;;=> this returns a java.time.LocalDate
    
    (m/decode schema "2024-01-01x" mett/time-transformer) ;;=> this returns the string "2024-01-01x" because decode silently ignores transformation that raise error
    
    (m/coerce schema "2024-01-01x" mett/time-transformer) ;;=> this raises an error
    
    (m/validate schema (m/decode schema "2024-01-01x" mett/time-transformer)) ;;=> this returns false
    
    (m/validate schema (m/decode schema "2024-01-01" mett/time-transformer)) ;;=> this returns true