validatornator/validators/
strings.rs

1use crate::utils::validation_error::ValidationError;
2use crate::utils::validation_result::ValidationResult;
3
4pub trait StringValidator {
5    fn be_not_empty(self) -> ValidationResult<String>;
6    fn be_longer_than(self, length: usize) -> ValidationResult<String>;
7    fn be_shorter_than(self, length: usize) -> ValidationResult<String>;
8}
9
10impl StringValidator for Result<String, ValidationError> {
11    fn be_not_empty(self) -> ValidationResult<String> {
12        match self {
13            Ok(value) => {
14                if value.is_empty() {
15                    Err(ValidationError::new("The string cannot be empty."))
16                } else {
17                    Ok(value)
18                }
19            },
20            error => error
21        }
22    }
23
24    fn be_longer_than(self, length: usize) -> ValidationResult<String> {
25        match self {
26            Ok(value) => {
27                if value.len() > length {
28                    Ok(value)
29                } else {
30                    Err(ValidationError::new(format!("The string must be longer than {} characters, but was {} instead.", length, value.len()).as_str()))
31                }
32            },
33            error => error
34        }
35    }
36
37    fn be_shorter_than(self, length: usize) -> ValidationResult<String> {
38        match self {
39            Ok(value) => {
40                if value.len() < length {
41                    Ok(value)
42                } else {
43                    Err(ValidationError::new(format!("The string must be shorter than {} characters, but was {} instead.", length, value.len()).as_str()))
44                }
45            },
46            error => error
47        }
48    }
49}