1pub struct Valid;
8
9impl Valid {
10 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 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 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 pub fn is_digits(s: &str) -> bool {
73 !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
74 }
75
76 pub fn is_alphanumeric(s: &str) -> bool {
78 !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric())
79 }
80
81 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 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 pub fn is_ipv4(s: &str) -> bool {
100 s.parse::<std::net::Ipv4Addr>().is_ok()
101 }
102
103 pub fn is_base64(s: &str) -> bool {
105 crate::Crypto::decode_base64(s).is_some()
106 }
107
108 pub fn is_uuid(s: &str) -> bool {
110 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 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 let tld = parts.last().unwrap();
146 tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic())
147 }
148
149 pub fn is_port(s: &str) -> bool {
151 s.parse::<u16>()
152 .map(|p| p > 0)
153 .unwrap_or(false)
154 }
155
156 pub fn is_chinese(s: &str) -> bool {
158 !s.is_empty() && s.chars().all(|c| !c.is_ascii() && c.is_alphabetic())
159 }
160
161 pub fn is_json(s: &str) -> bool {
163 serde_json::from_str::<serde_json::Value>(s).is_ok()
164 }
165
166 pub fn is_enum(s: &str, values: &[&str]) -> bool {
168 values.contains(&s)
169 }
170
171 pub fn is_empty(s: &str) -> bool {
173 s.trim().is_empty()
174 }
175
176 #[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 #[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 #[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 #[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 #[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#[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")); assert!(!Valid::is_uuid("not-a-uuid"));
300 assert!(!Valid::is_uuid("550e8400-e29b-41d4-a716")); }
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")); assert!(!Valid::is_domain(".com")); assert!(!Valid::is_domain("example.c")); }
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")); 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}