]> saetta.ns0.it Git - rust/zakform/commitdiff
Field's filters.
authorAndrea Zagli <azagli@libero.it>
Fri, 6 Jan 2023 10:27:46 +0000 (11:27 +0100)
committerAndrea Zagli <azagli@libero.it>
Fri, 6 Jan 2023 10:27:46 +0000 (11:27 +0100)
examples/form.rs
src/filters.rs [new file with mode: 0644]
src/lib.rs

index 79096097a6b8e089963045347aafaf15fa790b05..fa85845688d53a52ac8625a292b84b785ad1af50 100644 (file)
@@ -1,5 +1,7 @@
 extern crate zakform;
 
+use zakform::filters;
+
 use config::{Config, ConfigError};
 use serde_derive::Deserialize;
 
@@ -61,12 +63,16 @@ async fn index_post(
        let mut fi = zakform::Field::new(zakform::FType::Text, "name");
        fi.set_label("Name");
        fi.set_value(form.name.as_str());
+       fi.add_filter(filters::filter_uppercase);
+       fi.filter();
        f.add_field(fi);
 
        let mut fi = zakform::Field::new(zakform::FType::TextArea, "notes");
        fi.set_label("Notes");
        fi.set_rows(15);
        fi.set_value(form.notes.as_str());
+       fi.add_filter(filters::filter_trim);
+       fi.filter();
        f.add_field(fi);
 
        let fs = f.fields();
diff --git a/src/filters.rs b/src/filters.rs
new file mode 100644 (file)
index 0000000..e6e628f
--- /dev/null
@@ -0,0 +1,9 @@
+pub type Filter = fn(value: &String) -> String;
+
+pub fn filter_trim(value: &String) -> String {
+       String::from(value.trim())
+}
+
+pub fn filter_uppercase(value: &String) -> String {
+       value.to_uppercase()
+}
index 689f40f9858fe149768de18c9b95f5cf70c228ce..79e48ba367dee270bf4e8408dae67cea5f47de08 100644 (file)
@@ -1,5 +1,7 @@
 use tera::Tera;
 
+pub mod filters;
+
 pub enum FType {
        Text,
        TextArea
@@ -16,6 +18,7 @@ pub struct Field {
        help: String,
        value: String,
        tmpl: tera::Tera,
+       filters: Vec<filters::Filter>,
 }
 
 impl Field {
@@ -31,6 +34,7 @@ impl Field {
                        help: String::new(),
                        value: String::new(),
                        tmpl: Tera::default(),
+                       filters: vec![],
                };
 
                match f.ftype {
@@ -111,6 +115,16 @@ impl Field {
                self.value = String::from(value);
        }
 
+       pub fn add_filter(&mut self, filter: filters::Filter) {
+               self.filters.push(filter);
+       }
+
+       pub fn filter(&mut self) {
+               for f in &self.filters {
+                       self.value = (f)(&self.value);
+               }
+       }
+
        pub fn render(&self) -> String {
                let mut s = String::new();