malli

jobo3208 2025-12-29T23:04:06.124749Z

hello! i'm using mt/string-transformer to coerce data from a web form. i want to coerce empty strings to nil so that e.g. a blank field can be a valid value for a [:maybe :int] schema. is there a clear idiomatic way to do this?

Mathieu Lirzin 2025-12-30T11:46:29.478229Z

You can create your custom transformer for :maybe schemas with mt/transformer and compose it with mt/string-transformer. This is described here https://cljdoc.org/d/metosin/malli/0.19.1/doc/readme#advanced-transformations . In your case your custom transformer could look like this:

(require '[malli.core :as m]
         '[malli.transform :as mt]
         '[clojure.string :as str])

(defn blank->nil [x]
  (when-not (and (string? x) (str/blank? x))
    x))

(defn maybe-transformer []
  (mt/transformer
   {:name :maybe
    :decoders {:maybe blank->nil}}))

(def string-transformer
  (mt/transformer maybe-transformer mt/string-transformer))

(m/coerce [:maybe :int] "" string-transformer) ; => nil

jobo3208 2025-12-30T14:28:05.878289Z

perfect! i think using :maybe as the key for the decoder is what i missed. thank you!