use crate::core::validators::{EmailValidator, Validator};
use super::mixins::{FieldCacheMixin, FieldValidationMixin};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmailField {
pub max_length: usize,
}
impl Default for EmailField {
fn default() -> Self {
Self { max_length: 254 }
}
}
impl EmailField {
#[must_use]
pub fn new(max_length: usize) -> Self {
Self { max_length }
}
#[must_use]
pub fn max_length(&self) -> usize {
self.max_length
}
#[must_use]
pub fn db_type(&self) -> &str {
"VARCHAR"
}
}
impl FieldCacheMixin for EmailField {
fn get_cache_name(&self) -> String {
"email_field".to_string()
}
fn is_cached(&self) -> bool {
false
}
}
impl FieldValidationMixin for EmailField {
fn validate(&self, value: &str) -> Result<(), String> {
if value.chars().count() > self.max_length {
return Err(format!(
"Ensure this value has at most {} characters.",
self.max_length
));
}
EmailValidator::default()
.validate(&value)
.map_err(|error| error.message)
}
}
#[cfg(test)]
mod tests {
use super::EmailField;
#[test]
fn email_field_default_max_length_is_254() {
let field = EmailField::default();
assert_eq!(field.max_length, 254);
}
#[test]
fn email_field_new_sets_max_length() {
let field = EmailField::new(320);
assert_eq!(field.max_length(), 320);
}
}