type_rules/rules/
validate.rs

1use super::Rule;
2use crate::Validator;
3
4/// Rule to check the rules of the inner type
5///
6/// # Example
7/// ```
8/// use type_rules::prelude::*;
9///
10/// #[derive(Validator)]
11/// struct Password(#[rule(MinLength(8))] String);
12///
13/// #[derive(Validator)]
14/// struct User {
15///     username: String,
16///     #[rule(Validate())]
17///     password: Password,
18/// };
19/// ```
20pub struct Validate();
21
22impl<T: Validator> Rule<T> for Validate {
23    fn check(&self, value: &T) -> Result<(), String> {
24        value.check_validity()
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use crate::rules::{MaxLength, Rule, Validate};
31    use crate::Validator;
32    use claim::{assert_err, assert_ok};
33
34    struct StringWrapper(String);
35
36    impl Validator for StringWrapper {
37        fn check_validity(&self) -> Result<(), String> {
38            MaxLength(2).check(&self.0)
39        }
40    }
41
42    #[test]
43    fn validate_ok() {
44        assert_ok!(Validate().check(&StringWrapper(String::from("a"))));
45    }
46    #[test]
47    fn validate_err() {
48        assert_err!(Validate().check(&StringWrapper(String::from("aaa"))));
49    }
50}