Skip to content
This repository

Form Validation 

brentonashworth edited this page · 3 revisions

Home

In Sandbar, form validation is very simple. It is centered around the idea of a validation function. A validation function is a function which takes a map and returns an unaltered map if the contents pass validation. If validation fails, error information is added to the returned map.

Sandbar’s validation support is located in the sandbar.validation namespace.

The main functions that you will use from this namespace are:

  • add-validation-error
  • build-validator
  • non-empty-string
  • non-nil

The last two functions above are examples of built-in validators. Many more built-in validators will be added in the future.

Using add-validation-error

add-validation-error will add validation error information to a map in a form that can be retrieved by the form module and displayed to the user.

Below is a simple validator which will ensure that the value at key :x, in the map m, has more than 10 characters.

(defn length-validator [m]
  (if (< (count (:x m)) 10)
    (add-validation-error m :x "x must have 10 or more chars")
    m))

Composing validators

It is easy to compose several validators into one validator.

(defn compound-validator [m]
  (-> m
    validator-a
    validator-b
    (non-empty-string :name)))

Sometimes, validators can get complex.

(defn login-validator [m]
  (let [v (-> m
    (non-empty-string :username)
    (non-empty-string :password))]
    (if (= m v)
      (-> m
        password-validator)
        v)))

The build-validator macro is provided to make this simpler. The above validator could be written as:

(def login-validator
     (build-validator (non-empty-string :username)
                      (non-empty-string :password)
                      :ensure
                      password-validator))

Home
Stateful Sessions
Authentication and Authorization
Forms
Examples

Something went wrong with that request. Please try again.