Skip to content

Commit

Permalink
Add uri validator
Browse files Browse the repository at this point in the history
  • Loading branch information
swlkr committed Jan 31, 2020
1 parent 873fc96 commit c42ed5d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/joy/validator.janet
@@ -1,4 +1,5 @@
(import ./helper :as helper)
(import uri)

(defn- max-length? [len val]
(> (length val) len))
Expand All @@ -23,6 +24,12 @@
(not (empty? result)))))


(defn- uri? [val]
(when (string? val)
(->> (uri/parse val)
(helper/contains? :path))))


(defn- invalid-keys [ks dict pred]
(filter |(pred (get dict $))
ks))
Expand All @@ -49,20 +56,23 @@
:min-length min-length
:max-length max-length
:email email
:matches matches} validator
:matches matches
:uri uri} validator
msg (cond
(true? required) "is required"
(number? min-length) (string "needs to be more than " min-length " characters")
(number? max-length) (string "needs to be less than " max-length " characters")
(not (nil? email)) "needs to be an email"
(not (nil? matches)) (string "needs to match " (string/format "%q" matches))
(not (nil? uri)) (string "needs to be a valid uri " (string/format "%q" uri))
:else "")
predicate (cond
(true? required) blank?
(number? min-length) (partial min-length? min-length)
(number? max-length) (partial max-length? max-length)
(not (nil? email)) (comp not email?)
(not (nil? matches)) (partial (comp not matches-peg?) matches)
(not (nil? uri)) (comp not uri?)
:else identity)]
(let [invalid-ks (invalid-keys ks body predicate)]
(if (empty? invalid-ks)
Expand Down
9 changes: 8 additions & 1 deletion test/joy/validator-test.janet
Expand Up @@ -57,4 +57,11 @@
(helper/rescue)
(first)
(freeze))
{:name "name can't be blank"}))))
{:name "name can't be blank"})))

(let [test-params (params
(validates :website :uri true))]
(test "uri validator"
(= (-> (test-params {:body {:website "example.com"}})
(protect)
(last))))))

0 comments on commit c42ed5d

Please sign in to comment.