Skip to main content

wordval_utils/
valid.rs

1//! 常规验证工具:邮箱、手机、URL、身份证等
2
3/// 通用验证工具
4///
5/// 提供邮箱、手机号、URL、数字、字母数字、长度范围、
6/// 密码强度、IPv4、Base64 等常用格式的布尔校验方法。
7pub struct Valid;
8
9impl Valid {
10    /// 验证邮箱(手工实现,替代正则:本地部分 + `@` + 域部分含点 + 顶级域 2+ 字母)
11    pub fn is_email(s: &str) -> bool {
12        if s.is_empty() || s.len() > 254 {
13            return false;
14        }
15        let Some(at) = s.rfind('@') else {
16            return false;
17        };
18        if at == 0 || at == s.len() - 1 {
19            return false;
20        }
21        let (local, domain) = (&s[..at], &s[at + 1..]);
22        let local_ok = !local.starts_with('.')
23            && !local.ends_with('.')
24            && !local.contains("..")
25            && local
26                .chars()
27                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '%' | '+' | '-'));
28        if !local_ok {
29            return false;
30        }
31        let Some(dot) = domain.rfind('.') else {
32            return false;
33        };
34        if dot == 0 || dot == domain.len() - 1 {
35            return false;
36        }
37        let tld = &domain[dot + 1..];
38        tld.len() >= 2
39            && tld.chars().all(|c| c.is_ascii_alphabetic())
40            && domain
41                .chars()
42                .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
43    }
44
45    /// 验证手机号(中国大陆:1 开头,第二位 3-9,共 11 位数字)
46    pub fn is_mobile(s: &str) -> bool {
47        s.len() == 11
48            && s.starts_with('1')
49            && s.as_bytes()
50                .get(1)
51                .is_some_and(|b| (b'3'..=b'9').contains(b))
52            && s.bytes().all(|b| b.is_ascii_digit())
53    }
54
55    /// 验证 URL(http/https 协议,不含空白)
56    pub fn is_url(s: &str) -> bool {
57        let Some(rest) = s
58            .strip_prefix("http://")
59            .or_else(|| s.strip_prefix("https://"))
60        else {
61            return false;
62        };
63        let Some(first) = rest.chars().next() else {
64            return false;
65        };
66        !"/.$?#".contains(first)
67            && !first.is_whitespace()
68            && rest.chars().all(|c| !c.is_whitespace())
69    }
70
71    /// 验证是否为纯数字
72    pub fn is_digits(s: &str) -> bool {
73        !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
74    }
75
76    /// 验证是否为字母+数字组合
77    pub fn is_alphanumeric(s: &str) -> bool {
78        !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric())
79    }
80
81    /// 验证字符串长度范围
82    pub fn len_between(s: &str, min: usize, max: usize) -> bool {
83        let len = s.chars().count();
84        len >= min && len <= max
85    }
86
87    /// 验证密码强度(至少 8 位,包含大小写+数字)
88    pub fn is_strong_password(s: &str) -> bool {
89        if s.len() < 8 {
90            return false;
91        }
92        let has_lower = s.chars().any(|c| c.is_ascii_lowercase());
93        let has_upper = s.chars().any(|c| c.is_ascii_uppercase());
94        let has_digit = s.chars().any(|c| c.is_ascii_digit());
95        has_lower && has_upper && has_digit
96    }
97
98    /// 验证 IPv4
99    pub fn is_ipv4(s: &str) -> bool {
100        s.parse::<std::net::Ipv4Addr>().is_ok()
101    }
102
103    /// 验证 Base64
104    pub fn is_base64(s: &str) -> bool {
105        crate::Crypto::decode_base64(s).is_some()
106    }
107
108    /// 验证 UUID 格式(32 位 hex,可含连字符)
109    pub fn is_uuid(s: &str) -> bool {
110        // 单趟字节计数,零分配
111        let mut hex_count = 0u32;
112        for &b in s.as_bytes() {
113            if b == b'-' {
114                continue;
115            }
116            if !b.is_ascii_hexdigit() {
117                return false;
118            }
119            hex_count += 1;
120        }
121        hex_count == 32
122    }
123
124    /// 验证域名(至少一个点,每段字母数字+横线,顶级域 2+ 字母)
125    pub fn is_domain(s: &str) -> bool {
126        if s.is_empty() || s.len() > 253 {
127            return false;
128        }
129        let parts: Vec<&str> = s.split('.').collect();
130        if parts.len() < 2 {
131            return false;
132        }
133        for part in &parts {
134            if part.is_empty() || part.len() > 63 {
135                return false;
136            }
137            if part.starts_with('-') || part.ends_with('-') {
138                return false;
139            }
140            if !part.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
141                return false;
142            }
143        }
144        // 顶级域必须为纯字母且 2+ 字符
145        let tld = parts.last().unwrap();
146        tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic())
147    }
148
149    /// 验证端口号(1-65535)
150    pub fn is_port(s: &str) -> bool {
151        s.parse::<u16>()
152            .map(|p| p > 0)
153            .unwrap_or(false)
154    }
155
156    /// 验证是否全为中文字符
157    pub fn is_chinese(s: &str) -> bool {
158        !s.is_empty() && s.chars().all(|c| !c.is_ascii() && c.is_alphabetic())
159    }
160
161    /// 验证是否为合法 JSON
162    pub fn is_json(s: &str) -> bool {
163        serde_json::from_str::<serde_json::Value>(s).is_ok()
164    }
165
166    /// 验证是否在枚举值中
167    pub fn is_enum(s: &str, values: &[&str]) -> bool {
168        values.contains(&s)
169    }
170
171    /// 检查字符串是否为空(去除首尾空白后)
172    pub fn is_empty(s: &str) -> bool {
173        s.trim().is_empty()
174    }
175
176    /// 校验非空,失败返回 ApiError
177    #[cfg(feature = "validator-integration")]
178    pub fn not_empty(s: &str, field_name: &str) -> Result<(), wordval_core::api::ApiError> {
179        if Self::is_empty(s) {
180            Err(wordval_core::api::ApiError::bad_request(format!(
181                "{}不能为空",
182                field_name
183            )))
184        } else {
185            Ok(())
186        }
187    }
188
189    /// 通用条件校验 — condition 为 false 时返回 bad_request
190    #[cfg(feature = "validator-integration")]
191    #[track_caller]
192    pub fn must(
193        condition: bool,
194        msg: impl std::fmt::Display,
195    ) -> Result<(), wordval_core::api::ApiError> {
196        if condition {
197            Ok(())
198        } else {
199            Err(wordval_core::api::ApiError::bad_request(msg.to_string()))
200        }
201    }
202
203    /// 解包 Option,为 None 时返回 bad_request
204    ///
205    /// # 示例
206    ///
207    /// ```ignore
208    /// let code = Valid::required(payload.code.as_ref(), "验证码不能为空")?;
209    /// ```
210    #[cfg(feature = "validator-integration")]
211    #[track_caller]
212    pub fn required<T>(
213        value: Option<T>,
214        msg: impl Into<std::borrow::Cow<'static, str>>,
215    ) -> Result<T, wordval_core::api::ApiError> {
216        match value {
217            Some(v) => Ok(v),
218            None => Err(wordval_core::api::ApiError::bad_request(msg)),
219        }
220    }
221
222    /// 校验 actual < max,失败返回 bad_request
223    #[cfg(feature = "validator-integration")]
224    pub fn lt(
225        actual: u64,
226        max: u64,
227        msg: impl std::fmt::Display,
228    ) -> Result<(), wordval_core::api::ApiError> {
229        if actual < max {
230            Ok(())
231        } else {
232            Err(wordval_core::api::ApiError::bad_request(msg.to_string()))
233        }
234    }
235
236    /// 校验 slug 格式(小写字母、数字、中划线,不能以中划线开头或结尾,最长 64 字符)
237    #[cfg(feature = "validator-integration")]
238    pub fn slug(s: &str, field_name: &str) -> Result<(), wordval_core::api::ApiError> {
239        let ok = !s.is_empty()
240            && s.len() <= 64
241            && s.chars()
242                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
243            && !s.starts_with('-')
244            && !s.ends_with('-');
245        if ok {
246            Ok(())
247        } else {
248            Err(wordval_core::api::ApiError::bad_request(format!(
249                "{}只能包含小写字母、数字和中划线,不能以中划线开头或结尾",
250                field_name
251            )))
252        }
253    }
254}
255
256/// 将 validator crate 的 ValidationErrors 转换为可读的错误消息
257///
258/// 需要启用 `validator-integration` feature
259#[cfg(feature = "validator-integration")]
260impl Valid {
261    pub fn format_validation_errors(errors: &validator::ValidationErrors) -> String {
262        let mut messages = Vec::new();
263        for (field, field_errors) in errors.field_errors() {
264            for error in field_errors {
265                if let Some(msg) = &error.message {
266                    messages.push(format!("{}: {}", field, msg));
267                } else {
268                    messages.push(format!("{}: {}", field, error.code));
269                }
270            }
271        }
272        messages.join("; ")
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    #[test]
280    fn test_email() {
281        assert!(Valid::is_email("a@b.com"));
282        assert!(!Valid::is_email("not-email"));
283    }
284    #[test]
285    fn test_mobile() {
286        assert!(Valid::is_mobile("13812345678"));
287        assert!(!Valid::is_mobile("1234"));
288    }
289    #[test]
290    fn test_password() {
291        assert!(Valid::is_strong_password("Abcdefg1"));
292        assert!(!Valid::is_strong_password("123456"));
293    }
294
295    #[test]
296    fn test_is_uuid() {
297        assert!(Valid::is_uuid("550e8400-e29b-41d4-a716-446655440000"));
298        assert!(Valid::is_uuid("550e8400e29b41d4a716446655440000")); // 无连字符
299        assert!(!Valid::is_uuid("not-a-uuid"));
300        assert!(!Valid::is_uuid("550e8400-e29b-41d4-a716")); // 太短
301    }
302
303    #[test]
304    fn test_is_domain() {
305        assert!(Valid::is_domain("example.com"));
306        assert!(Valid::is_domain("sub.example.co.uk"));
307        assert!(!Valid::is_domain("localhost")); // 无点
308        assert!(!Valid::is_domain(".com")); // 空段
309        assert!(!Valid::is_domain("example.c")); // TLD 太短
310    }
311
312    #[test]
313    fn test_is_port() {
314        assert!(Valid::is_port("80"));
315        assert!(Valid::is_port("443"));
316        assert!(Valid::is_port("65535"));
317        assert!(!Valid::is_port("0"));
318        assert!(!Valid::is_port("65536"));
319        assert!(!Valid::is_port("abc"));
320    }
321
322    #[test]
323    fn test_is_chinese() {
324        assert!(Valid::is_chinese("中文"));
325        assert!(Valid::is_chinese("你好世界"));
326        assert!(!Valid::is_chinese("中文abc")); // 含英文
327        assert!(!Valid::is_chinese(""));
328        assert!(!Valid::is_chinese("123"));
329    }
330
331    #[test]
332    fn test_is_json() {
333        assert!(Valid::is_json("{\"key\": \"value\"}"));
334        assert!(Valid::is_json("[1, 2, 3]"));
335        assert!(Valid::is_json("\"string\""));
336        assert!(!Valid::is_json("{invalid}"));
337        assert!(!Valid::is_json(""));
338    }
339
340    #[test]
341    fn test_is_enum() {
342        assert!(Valid::is_enum("active", &["active", "inactive", "pending"]));
343        assert!(!Valid::is_enum("deleted", &["active", "inactive", "pending"]));
344    }
345}