1use serde_json::{json, Value};
2
3use crate::validator::{Rule, ValidError, ValidResult, Validator};
4
5#[derive(Debug, Default)]
6pub struct Email;
7
8impl Rule<&str> for Email {
9 fn valid(&self, value: &str, field_path: &str, message: Option<String>) -> ValidResult {
10 if value.contains('@') && value.contains('.') {
11 Ok(())
12 } else {
13 Err(ValidError { message: message.unwrap_or_else(|| format!("{} is not email", field_path)) })
14 }
15 }
16 fn example(&self) -> Vec<Value> {
17 vec![json!("1111@qq.com")]
18 }
19}
20
21#[derive(Debug, Default)]
22pub struct Number {
23 max_limit: Option<isize>,
24 min_limit: Option<isize>,
25}
26
27impl Number {
28 pub fn max(mut self, v: isize) -> Self {
29 self.max_limit = Some(v);
30 self
31 }
32
33 pub fn min(mut self, v: isize) -> Self {
34 self.min_limit = Some(v);
35 self
36 }
37}
38
39impl Rule<&isize> for Number {
40 fn valid(&self, value: &isize, field_path: &str, message: Option<String>) -> ValidResult {
41 let field_path = field_path.to_string();
42 if let Some(max) = self.max_limit {
43 if *value > max {
44 return Err(ValidError { message: message.unwrap_or_else(|| format!("{} > min", field_path)) });
45 }
46 }
47 if let Some(min) = self.min_limit {
48 if *value < min {
49 return Err(ValidError { message: message.unwrap_or_else(|| format!("{} > max", field_path)) });
50 }
51 }
52 Ok(())
53 }
54 fn example(&self) -> Vec<Value> {
55 vec![json!(122)]
56 }
57}
58
59impl Rule<&i32> for Number {
60 fn valid(&self, value: &i32, field_path: &str, message: Option<String>) -> ValidResult {
61 let value = *value as isize;
62 Number::valid(self, &value, field_path, message)
63 }
64
65 fn example(&self) -> Vec<Value> {
66 vec![json!(122)]
67 }
68}
69
70pub struct Valid<'a, T: Validator>(pub &'a T);
71
72impl<'a, T: Validator> Rule<&T> for Valid<'a, T> {
73 fn valid(&self, value: &T, field_path: &str, message: Option<String>) -> ValidResult {
74 self.0.valid()
75 }
76 fn example(&self) -> Vec<Value> {
77 self.0.example()
78 }
79}