const COLOR_LENGTH: usize = 7;
const ALPHANUMERIC_COUNT: usize = 6;
use crate::errors::ValidationError;
pub trait Validation {
fn validate_color_code(&self) -> Result<bool, ValidationError>;
}
impl Validation for &str {
fn validate_color_code(&self) -> Result<bool, ValidationError> {
if self.chars().nth(0) != Some('#') {
return Err(ValidationError::new(
"Color should be in the #hex format (e.g #000000) for black",
));
}
if self.len() != COLOR_LENGTH {
return Err(ValidationError::new(
"Color should be in the #hex format (e.g #000000) for black",
));
}
let mut split_color = self.split("#");
split_color.next();
let color_code_chars = split_color
.next()
.expect("Invalid color. It should be in the #hex format (e.g #000000 for black)")
.chars();
let filtered_chars = color_code_chars
.filter(|char| char.is_alphanumeric())
.collect::<Vec<_>>();
if filtered_chars.len() != ALPHANUMERIC_COUNT {
return Err(ValidationError::new(
"Color should be in the #hex format (e.g #000000) for black",
));
}
Ok(true)
}
}