metosin / malli

High-performance data-driven data specification library for Clojure/Script.
Eclipse Public License 2.0
1.43k stars 204 forks source link

allow :error/fn or :error/message in {:optional t/f} to help define missing key error message #1050

Open danielspaniel opened 2 months ago

danielspaniel commented 2 months ago

Let's say I have a schema like this for a party

[:map 
    [:party/type {:optional false} [:or [:= "company-type"] [:= "person-type"]]]
    [:party/company-name {:optional false} :string]
    [:party/person-name {:optional true} :string]]

I was thinking it would be nice to have an option like this

[:map 
     [:party/type {:optional false} [:or [:= "company-type"] [:= "person-type"]]]
     [:party/company-name {:optional false :error/message "company name is required for party type 'company-type'" } :string]
     [:party/person-name {:optional true} :string]]

rather than having to pass the error message for missing key like this


  (me/humanize (m/explain schema party)
      {:errors (-> me/default-errors
                 (assoc ::m/missing-key {:error/fn (fn [{:keys [in]} e]
                                                     (str "company name is required " (last in)))}))})```

  having both :error/message or  :error/fn  where the function passes me the error would be ideal   since the schema now contains all it needs to output good error messages

   having to use the me/default errors seems clunky to me and requires extra step to keep those messing key maps around when I could put them right on the schema 

  If you approve of this I am willing to try and implement it