From 79923a7579b784b891e2843f31449f51741b2d60 Mon Sep 17 00:00:00 2001 From: Josha von Gizycki Date: Thu, 11 Oct 2018 10:09:06 +0200 Subject: [PATCH] valid? receives transformed form-data, executes form-specs --- src/formulare/core.clj | 65 ++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/src/formulare/core.clj b/src/formulare/core.clj index d67ba53..a55175e 100644 --- a/src/formulare/core.clj +++ b/src/formulare/core.clj @@ -33,19 +33,43 @@ (spec/keys :req-un [::fields] :opt-un [::form-specs])) -(defn valid? [form-def req] - {:pre [(spec/assert ::form form-def)]} +(defn form-data [form-def req] + (when-not (spec/valid? ::form form-def) + (throw (ex-info "Form def fails spec" (spec/explain-data ::form form-def)))) + (reduce (fn [coll [id field]] + (let [value (get-in req [:params id])] + (assoc coll + id + (if-let [from-req (:from-req field)] + (from-req value) + value)))) + {} + (:fields form-def))) + +(defn form-specs-valid? [form-def data] + (reduce (fn [valid? field-spec] + (if (spec/valid? field-spec data) + true + (reduced false))) + true + (:form-specs form-def))) + +(defn field-specs-valid? [form-def data] (reduce-kv - (fn [result field value] - (if-let [field-spec (get-in form-def [:fields field :spec])] - (let [from-req (get-in form-def [:fields field :from-req]) - check-value (if from-req (from-req value) value)] - (if (spec/valid? field-spec check-value) - true - (reduced false))) + (fn [result field field-def] + (if-let [field-spec (:spec field-def)] + (if (spec/valid? field-spec (field data)) + true + (reduced false)) result)) true - (:params req))) + (:fields form-def))) + +(defn valid? [form-def req] + {:pre [(spec/assert ::form form-def)]} + (let [data (form-data form-def req)] + (and (field-specs-valid? form-def data) + (form-specs-valid? form-def data)))) (def ^:dynamic *row-theme* theme/row) (def ^:dynamic *widget-error-theme* theme/widget-error) @@ -74,14 +98,6 @@ (*label-theme* id def) (renderer id def (if validate? req-value value))))) -(defn form-specs-valid? [form-def req] - (reduce (fn [valid? field-spec] - (if (spec/valid? field-spec (:params req)) - true - (reduced false))) - true - (:form-specs form-def))) - (defn form-hash [form-def values] (str (hash [form-def values]))) @@ -110,16 +126,3 @@ [form-errors]) all-widgets) all-widgets))) - -(defn form-data [form-def req] - (when-not (spec/valid? ::form form-def) - (throw (ex-info "Form def fails spec" (spec/explain-data ::form form-def)))) - (reduce (fn [coll [id field]] - (let [value (get-in req [:params id])] - (assoc coll - id - (if-let [from-req (:from-req field)] - (from-req value) - value)))) - {} - (:fields form-def)))