Skip to content

Commit

Permalink
doc
Browse files Browse the repository at this point in the history
  • Loading branch information
tu6ge committed May 26, 2024
1 parent 70168cb commit d54406b
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
57 changes: 57 additions & 0 deletions examples/string_custom.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use valitron::{
available::{Email, Trim},
register::string::Validator,
rule::string::{StringRule, StringRuleExt},
};

pub fn main() {
let data = Input {
name: " Jone ".into(),
email: "jone@gmail.com".into(),
gender: "male".into(),
password: "Abc123".into(),
age: 12,
weight: 101.2,
};

let data = Input::new(data).unwrap();

assert_eq!(data.name, "Jone");
}

struct Input {
name: String,
email: String,
gender: String,
password: String,
age: u8,
weight: f32,
}

impl Input {
fn new(mut input: Input) -> Result<Self, Validator<String>> {
let valid = Validator::new()
.insert("name", &mut input.name, Trim)
.insert("email", &mut input.email, Trim.and(Email))
.map(Into::<String>::into)
.insert("name", &mut input.name, MyRequired("name"))
.insert("email", &mut input.email, MyRequired("email"));

valid.validate(input)
}
}

#[derive(Debug, Clone)]
struct MyRequired<'a>(&'a str);

impl StringRule for MyRequired<'_> {
type Message = String;
const NAME: &'static str = "my_required";
fn call(&mut self, data: &mut String) -> bool {
!data.is_empty()
}

fn message(&self) -> Self::Message {
format!("{} is not be empty", self.0)
}
}
5 changes: 5 additions & 0 deletions src/register/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@
//! }
//!
//! ```
//!
//! This validator is highly abstract, This means that you can use custom rules,They can also be used together with build-in rules,
//! This only need to converting the error types they return.
//!
//! > custom rule need to implement Clone.

use std::collections::HashMap;

Expand Down

0 comments on commit d54406b

Please sign in to comment.