2

How to validate date in malli schema? What is the data type that I must use?

I checked with local-date, but its not valid in clojure. This is the code I followed.

(def date (m/schema [:map
                   [:a :int]
                   [:b :re #"\d{4}-\d{2}-\d{2}"]
                   ]))

Thsi worked fine when I validated.

(m/validate s2 {:a 1 :b "2022-07-28"})
=> true

But when I try to convert this to Json schema, I get error as such.

(def s2 [:map 
         [:orderId string?]
         [:OrderDate :re "\d{4}-\d{2}-\d{2}"]
         ])
Syntax error reading source at (REPL:3:24).
Unsupported escape character: \d

So how must in resolve this? Edit : Reslved. Use it as

:re #"\d{4}-\d{2}-\d{2}" OR [:re "\d{4}-\d{2}-\d{2}"]

But now validation fails :

(m/validate s2 {:a 1 :b "2022-07-28"})
=> false
MouseNag
  • 303
  • 1
  • 9

1 Answers1

2

This seems to work:

Dependency: [metosin/malli "0.8.9"]

Require: [malli.json-schema :as json-schema]

(json-schema/transform [:map
                        [:order-id :string]
                        [:order-date [:re #"\d{4}-\d{2}-\d{2}"]]])
=>
{:type "object",
 :properties {:order-id {:type "string"}, :order-date {:type "string", :pattern #"\d{4}-\d{2}-\d{2}"}},
 :required [:order-id :order-date]}

You can also take a look at a pull request aiming to add java.time dates into Malli, maybe you'll find something useful here.

Martin Půda
  • 7,353
  • 2
  • 6
  • 13
  • Yes this works. And this too : (def s2 [:map [:acctId string?] [:date :re #"\d{4}-\d{2}-\d{2}"] ]) But validation fails: (m/validate s2 {:a 1 :b "2022-07-28"}) => false – MouseNag Aug 01 '22 at 02:33
  • 1
    It seems that keys in the map must have exactly these names (and your map also contains `int` instead of `string`), so here is an example that returns true: `(def s2 [:map [:acctId string?] [:date :re #"\d{4}-\d{2}-\d{2}"]])` `(m/validate s2 {:acctId "1" :date "2022-07-28"})` – Martin Půda Aug 01 '22 at 03:04
  • This works! The problem was here : (and your map also contains int instead of string) – MouseNag Aug 01 '22 at 05:13