Last active
July 1, 2021 12:15
-
-
Save yuk1ty/16af4a0a6e8c143a390f047bf752c0d0 to your computer and use it in GitHub Desktop.
Create string type validated
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{marker::PhantomData, str::FromStr}; | |
use super::error::ValidationError; | |
pub trait ValidationStrategy { | |
fn validate(target: &str) -> Result<String, ValidationError>; | |
} | |
pub struct NonEmptyString<V> | |
where | |
V: ValidationStrategy, | |
{ | |
pub value: String, | |
_marker: PhantomData<fn() -> V>, | |
} | |
pub mod rules { | |
use super::ValidationStrategy; | |
use crate::types::error::ValidationError; | |
pub struct LessThanEqualFour; | |
impl ValidationStrategy for LessThanEqualFour { | |
fn validate(target: &str) -> Result<String, ValidationError> { | |
if target.len() <= 4 { | |
Ok(target.to_string()) | |
} else { | |
Err(ValidationError::InvalidFormat(format!( | |
"{} must be less than equal 4", | |
&target | |
))) | |
} | |
} | |
} | |
pub struct LessThanEqualEight; | |
impl ValidationStrategy for LessThanEqualEight { | |
fn validate(target: &str) -> Result<String, ValidationError> { | |
if target.len() <= 8 { | |
Ok(target.to_string()) | |
} else { | |
Err(ValidationError::InvalidFormat(format!( | |
"{} must be less than equal 8", | |
&target | |
))) | |
} | |
} | |
} | |
} | |
impl<T> FromStr for NonEmptyString<T> | |
where | |
T: ValidationStrategy, | |
{ | |
type Err = ValidationError; | |
fn from_str(s: &str) -> Result<Self, Self::Err> { | |
if s.is_empty() { | |
return Err(ValidationError::NotAllowedEmpty); | |
} | |
let validated = T::validate(s)?; | |
Ok(NonEmptyString { | |
value: validated, | |
_marker: PhantomData, | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment