garde/rules/
alphanumeric.rs

1//! Alphanumeric validation.
2//!
3//! ```rust
4//! #[derive(garde::Validate)]
5//! struct Test {
6//!     #[garde(alphanumeric)]
7//!     v: String,
8//! }
9//! ```
10//!
11//! The entrypoint is the [`Alphanumeric`] trait. Implementing this trait for a type allows that type to be used with the `#[garde(alphanumeric)]` rule.
12//!
13//! This trait has a blanket implementation for all `T: garde::rules::AsStr`.
14
15use super::AsStr;
16use crate::error::Error;
17
18pub fn apply<T: Alphanumeric>(v: &T, _: ()) -> Result<(), Error> {
19    if !v.validate_alphanumeric() {
20        return Err(Error::new("not alphanumeric"));
21    }
22    Ok(())
23}
24
25pub trait Alphanumeric {
26    fn validate_alphanumeric(&self) -> bool;
27}
28
29impl<T: AsStr> Alphanumeric for T {
30    fn validate_alphanumeric(&self) -> bool {
31        self.as_str().chars().all(|c| c.is_alphanumeric())
32    }
33}
34
35impl<T: Alphanumeric> Alphanumeric for Option<T> {
36    fn validate_alphanumeric(&self) -> bool {
37        match self {
38            Some(value) => value.validate_alphanumeric(),
39            None => true,
40        }
41    }
42}