red-tape / docs / 03-cleaners.markdown

Cleaners

Cleaners are the workhorses of Red Tape. They massage your form's data into the shape you want, and detect bad data so you can bail out if necessary.

Cleaners are Functions

Cleaners are plain old Clojure functions -- there's nothing special about them. They take one argument (the data to clean) and return a result.

Here are a few examples:

; A cleaner to turn the raw string into a Long.
(defn to-long [v]
  (Long. v))

; A cleaner to take a Long user ID and look up the
; user in a database.
(def users {1 "Steve"})

(defn to-user [id]
  (let [user (get users id)]
    (if user
      user
      (throw+ "Invalid user ID!"))))

; Use both of these cleaners to first turn the input
; string into a long, then into a user.
(defform user-form {}
  :user [to-long to-user])

; Now we'll call the form with some data.
(user-form {"user" "1"})
; =>
{:valid true
 :results {:user "Steve"}
 ...}

Validation Errors

Cleaners can report a validation error by throwing an exception, or by using Slingshot's throw+ to throw anything.

If a cleaner throws something, the result map's :valid entry will be false and the :errors entry will contain whatever was thrown. Continuing the example above:

(user-form {"user" "400"})
; =>
{:valid false
 :errors {:user "Invalid user ID!"}
 ...}

Form-Level Cleaners

Built-In Cleaners

Red Tape contains a number of common cleaners in red-tape.cleaners. See the Reference section for the full list.

Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.