wordval-utils 1.0.2

Wordval utilities: string manipulation, date handling, masking, ID generation, validation, crypto, web helpers, collection tools, retry utilities
Documentation
//! 常规验证工具:邮箱、手机、URL、身份证等

/// 通用验证工具
///
/// 提供邮箱、手机号、URL、数字、字母数字、长度范围、
/// 密码强度、IPv4、Base64 等常用格式的布尔校验方法。
pub struct Valid;

impl Valid {
    /// 验证邮箱(手工实现,替代正则:本地部分 + `@` + 域部分含点 + 顶级域 2+ 字母)
    pub fn is_email(s: &str) -> bool {
        if s.is_empty() || s.len() > 254 {
            return false;
        }
        let Some(at) = s.rfind('@') else {
            return false;
        };
        if at == 0 || at == s.len() - 1 {
            return false;
        }
        let (local, domain) = (&s[..at], &s[at + 1..]);
        let local_ok = !local.starts_with('.')
            && !local.ends_with('.')
            && !local.contains("..")
            && local
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '%' | '+' | '-'));
        if !local_ok {
            return false;
        }
        let Some(dot) = domain.rfind('.') else {
            return false;
        };
        if dot == 0 || dot == domain.len() - 1 {
            return false;
        }
        let tld = &domain[dot + 1..];
        tld.len() >= 2
            && tld.chars().all(|c| c.is_ascii_alphabetic())
            && domain
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
    }

    /// 验证手机号(中国大陆:1 开头,第二位 3-9,共 11 位数字)
    pub fn is_mobile(s: &str) -> bool {
        s.len() == 11
            && s.starts_with('1')
            && s.as_bytes()
                .get(1)
                .is_some_and(|b| (b'3'..=b'9').contains(b))
            && s.bytes().all(|b| b.is_ascii_digit())
    }

    /// 验证 URL(http/https 协议,不含空白)
    pub fn is_url(s: &str) -> bool {
        let Some(rest) = s
            .strip_prefix("http://")
            .or_else(|| s.strip_prefix("https://"))
        else {
            return false;
        };
        let Some(first) = rest.chars().next() else {
            return false;
        };
        !"/.$?#".contains(first)
            && !first.is_whitespace()
            && rest.chars().all(|c| !c.is_whitespace())
    }

    /// 验证是否为纯数字
    pub fn is_digits(s: &str) -> bool {
        !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
    }

    /// 验证是否为字母+数字组合
    pub fn is_alphanumeric(s: &str) -> bool {
        !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric())
    }

    /// 验证字符串长度范围
    pub fn len_between(s: &str, min: usize, max: usize) -> bool {
        let len = s.chars().count();
        len >= min && len <= max
    }

    /// 验证密码强度(至少 8 位,包含大小写+数字)
    pub fn is_strong_password(s: &str) -> bool {
        if s.len() < 8 {
            return false;
        }
        let has_lower = s.chars().any(|c| c.is_ascii_lowercase());
        let has_upper = s.chars().any(|c| c.is_ascii_uppercase());
        let has_digit = s.chars().any(|c| c.is_ascii_digit());
        has_lower && has_upper && has_digit
    }

    /// 验证 IPv4
    pub fn is_ipv4(s: &str) -> bool {
        s.parse::<std::net::Ipv4Addr>().is_ok()
    }

    /// 验证 Base64
    pub fn is_base64(s: &str) -> bool {
        crate::Crypto::decode_base64(s).is_some()
    }

    /// 验证 UUID 格式(32 位 hex,可含连字符)
    pub fn is_uuid(s: &str) -> bool {
        let hex: String = s.chars().filter(|c| *c != '-').collect();
        hex.len() == 32 && hex.chars().all(|c| c.is_ascii_hexdigit())
    }

    /// 验证域名(至少一个点,每段字母数字+横线,顶级域 2+ 字母)
    pub fn is_domain(s: &str) -> bool {
        if s.is_empty() || s.len() > 253 {
            return false;
        }
        let parts: Vec<&str> = s.split('.').collect();
        if parts.len() < 2 {
            return false;
        }
        for part in &parts {
            if part.is_empty() || part.len() > 63 {
                return false;
            }
            if part.starts_with('-') || part.ends_with('-') {
                return false;
            }
            if !part.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
                return false;
            }
        }
        // 顶级域必须为纯字母且 2+ 字符
        let tld = parts.last().unwrap();
        tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic())
    }

    /// 验证端口号(1-65535)
    pub fn is_port(s: &str) -> bool {
        s.parse::<u16>()
            .map(|p| p > 0)
            .unwrap_or(false)
    }

    /// 验证是否全为中文字符
    pub fn is_chinese(s: &str) -> bool {
        !s.is_empty() && s.chars().all(|c| c.is_ascii() == false && c.is_alphabetic())
    }

    /// 验证是否为合法 JSON
    pub fn is_json(s: &str) -> bool {
        serde_json::from_str::<serde_json::Value>(s).is_ok()
    }

    /// 验证是否在枚举值中
    pub fn is_enum(s: &str, values: &[&str]) -> bool {
        values.contains(&s)
    }

    /// 检查字符串是否为空(去除首尾空白后)
    pub fn is_empty(s: &str) -> bool {
        s.trim().is_empty()
    }

    /// 校验非空,失败返回 ApiError
    #[cfg(feature = "validator-integration")]
    pub fn not_empty(s: &str, field_name: &str) -> Result<(), wordval_core::api::ApiError> {
        if Self::is_empty(s) {
            Err(wordval_core::api::ApiError::bad_request(format!(
                "{}不能为空",
                field_name
            )))
        } else {
            Ok(())
        }
    }

    /// 通用条件校验 — condition 为 false 时返回 bad_request
    #[cfg(feature = "validator-integration")]
    #[track_caller]
    pub fn must(
        condition: bool,
        msg: impl std::fmt::Display,
    ) -> Result<(), wordval_core::api::ApiError> {
        if condition {
            Ok(())
        } else {
            Err(wordval_core::api::ApiError::bad_request(msg.to_string()))
        }
    }

    /// 解包 Option,为 None 时返回 bad_request
    ///
    /// # 示例
    ///
    /// ```ignore
    /// let code = Valid::required(payload.code.as_ref(), "验证码不能为空")?;
    /// ```
    #[cfg(feature = "validator-integration")]
    #[track_caller]
    pub fn required<T>(
        value: Option<T>,
        msg: impl Into<std::borrow::Cow<'static, str>>,
    ) -> Result<T, wordval_core::api::ApiError> {
        match value {
            Some(v) => Ok(v),
            None => Err(wordval_core::api::ApiError::bad_request(msg)),
        }
    }

    /// 校验 actual < max,失败返回 bad_request
    #[cfg(feature = "validator-integration")]
    pub fn lt(
        actual: u64,
        max: u64,
        msg: impl std::fmt::Display,
    ) -> Result<(), wordval_core::api::ApiError> {
        if actual < max {
            Ok(())
        } else {
            Err(wordval_core::api::ApiError::bad_request(msg.to_string()))
        }
    }

    /// 校验 slug 格式(小写字母、数字、中划线,不能以中划线开头或结尾,最长 64 字符)
    #[cfg(feature = "validator-integration")]
    pub fn slug(s: &str, field_name: &str) -> Result<(), wordval_core::api::ApiError> {
        let ok = !s.is_empty()
            && s.len() <= 64
            && s.chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
            && !s.starts_with('-')
            && !s.ends_with('-');
        if ok {
            Ok(())
        } else {
            Err(wordval_core::api::ApiError::bad_request(format!(
                "{}只能包含小写字母、数字和中划线,不能以中划线开头或结尾",
                field_name
            )))
        }
    }
}

/// 将 validator crate 的 ValidationErrors 转换为可读的错误消息
///
/// 需要启用 `validator-integration` feature
#[cfg(feature = "validator-integration")]
impl Valid {
    pub fn format_validation_errors(errors: &validator::ValidationErrors) -> String {
        let mut messages = Vec::new();
        for (field, field_errors) in errors.field_errors() {
            for error in field_errors {
                if let Some(msg) = &error.message {
                    messages.push(format!("{}: {}", field, msg));
                } else {
                    messages.push(format!("{}: {}", field, error.code));
                }
            }
        }
        messages.join("; ")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_email() {
        assert!(Valid::is_email("a@b.com"));
        assert!(!Valid::is_email("not-email"));
    }
    #[test]
    fn test_mobile() {
        assert!(Valid::is_mobile("13812345678"));
        assert!(!Valid::is_mobile("1234"));
    }
    #[test]
    fn test_password() {
        assert!(Valid::is_strong_password("Abcdefg1"));
        assert!(!Valid::is_strong_password("123456"));
    }

    #[test]
    fn test_is_uuid() {
        assert!(Valid::is_uuid("550e8400-e29b-41d4-a716-446655440000"));
        assert!(Valid::is_uuid("550e8400e29b41d4a716446655440000")); // 无连字符
        assert!(!Valid::is_uuid("not-a-uuid"));
        assert!(!Valid::is_uuid("550e8400-e29b-41d4-a716")); // 太短
    }

    #[test]
    fn test_is_domain() {
        assert!(Valid::is_domain("example.com"));
        assert!(Valid::is_domain("sub.example.co.uk"));
        assert!(!Valid::is_domain("localhost")); // 无点
        assert!(!Valid::is_domain(".com")); // 空段
        assert!(!Valid::is_domain("example.c")); // TLD 太短
    }

    #[test]
    fn test_is_port() {
        assert!(Valid::is_port("80"));
        assert!(Valid::is_port("443"));
        assert!(Valid::is_port("65535"));
        assert!(!Valid::is_port("0"));
        assert!(!Valid::is_port("65536"));
        assert!(!Valid::is_port("abc"));
    }

    #[test]
    fn test_is_chinese() {
        assert!(Valid::is_chinese("中文"));
        assert!(Valid::is_chinese("你好世界"));
        assert!(!Valid::is_chinese("中文abc")); // 含英文
        assert!(!Valid::is_chinese(""));
        assert!(!Valid::is_chinese("123"));
    }

    #[test]
    fn test_is_json() {
        assert!(Valid::is_json("{\"key\": \"value\"}"));
        assert!(Valid::is_json("[1, 2, 3]"));
        assert!(Valid::is_json("\"string\""));
        assert!(!Valid::is_json("{invalid}"));
        assert!(!Valid::is_json(""));
    }

    #[test]
    fn test_is_enum() {
        assert!(Valid::is_enum("active", &["active", "inactive", "pending"]));
        assert!(!Valid::is_enum("deleted", &["active", "inactive", "pending"]));
    }
}