async-graphql/src/validators/min_length.rs

30 lines
677 B
Rust
Raw Normal View History

2021-11-14 13:09:14 +00:00
use crate::{InputType, InputValueError};
2021-11-15 01:12:13 +00:00
pub fn min_length<T: AsRef<str> + InputType>(
2021-11-14 13:09:14 +00:00
value: &T,
len: usize,
) -> Result<(), InputValueError<T>> {
if value.as_ref().len() >= len {
Ok(())
} else {
Err(format!(
"the string length is {}, must be greater than or equal to {}",
value.as_ref().len(),
len
)
.into())
}
}
2021-11-15 03:08:56 +00:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min_length() {
assert!(min_length(&"ab".to_string(), 3).is_err());
assert!(min_length(&"abc".to_string(), 3).is_ok());
assert!(min_length(&"abcd".to_string(), 3).is_ok());
}
}