1use crate::error::BaseError;
6#[cfg(feature = "validator")]
7use regex::Regex;
8use serde::{Deserialize, Serialize};
9#[cfg(feature = "validator")]
10use std::collections::HashMap;
11use std::sync::Arc;
12#[cfg(feature = "validator")]
13use std::sync::{OnceLock, RwLock};
14
15pub type ValidatorFn = Arc<dyn Fn(&str, &serde_json::Value) -> Result<(), BaseError> + Send + Sync>;
19
20#[cfg(feature = "validator")]
24static EMAIL_REGEX: OnceLock<Regex> = OnceLock::new();
25
26#[cfg(feature = "validator")]
28static PHONE_REGEX: OnceLock<Regex> = OnceLock::new();
29
30#[cfg(feature = "validator")]
34static REGEX_CACHE: OnceLock<RwLock<HashMap<String, Regex>>> = OnceLock::new();
35
36#[cfg(feature = "validator")]
38fn email_regex() -> &'static Regex {
39 EMAIL_REGEX.get_or_init(|| {
40 Regex::new(r"^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
42 .expect("邮箱正则表达式编译失败")
43 })
44}
45
46#[cfg(feature = "validator")]
48fn phone_regex() -> &'static Regex {
49 PHONE_REGEX.get_or_init(|| {
50 Regex::new(r"^\+?[1-9]\d{1,14}$").expect("手机号正则表达式编译失败")
52 })
53}
54
55#[derive(Clone)]
57pub enum Validator {
58 MinLength(usize),
60 MaxLength(usize),
62 Min(f64),
64 Max(f64),
66 Email,
68 EmailLoose,
70 Phone,
72 PhoneLoose,
74 Url,
88 Regex(String),
90 Custom(ValidatorFn),
92}
93
94impl Validator {
95 pub fn display_name(&self) -> &str {
97 match self {
98 Validator::MinLength(_) => "最小长度",
99 Validator::MaxLength(_) => "最大长度",
100 Validator::Min(_) => "最小值",
101 Validator::Max(_) => "最大值",
102 Validator::Email => "邮箱格式(严格)",
103 Validator::EmailLoose => "邮箱格式(宽松)",
104 Validator::Phone => "手机号格式(严格)",
105 Validator::PhoneLoose => "手机号格式(宽松)",
106 Validator::Url => "URL格式",
107 Validator::Regex(_) => "正则表达式",
108 Validator::Custom(_) => "自定义验证",
109 }
110 }
111
112 pub fn validate(&self, field_name: &str, value: &serde_json::Value) -> Result<(), BaseError> {
114 match self {
115 Validator::MinLength(min_len) => {
116 if let Some(s) = value.as_str() {
117 let len = s.chars().count();
118 if len < *min_len {
119 return Err(BaseError::ValidationFailed(
120 field_name.to_string(),
121 format!("字符串长度不能小于 {},当前长度: {}", min_len, len),
122 ));
123 }
124 Ok(())
125 } else {
126 Err(BaseError::ValidationFailed(
127 field_name.to_string(),
128 "MinLength 验证器只能用于字符串类型".to_string(),
129 ))
130 }
131 }
132
133 Validator::MaxLength(max_len) => {
134 if let Some(s) = value.as_str() {
135 let len = s.chars().count();
136 if len > *max_len {
137 return Err(BaseError::ValidationFailed(
138 field_name.to_string(),
139 format!("字符串长度不能大于 {},当前长度: {}", max_len, len),
140 ));
141 }
142 Ok(())
143 } else {
144 Err(BaseError::ValidationFailed(
145 field_name.to_string(),
146 "MaxLength 验证器只能用于字符串类型".to_string(),
147 ))
148 }
149 }
150
151 Validator::Min(min_val) => {
152 let num = if let Some(n) = value.as_f64() {
153 n
154 } else if let Some(n) = value.as_i64() {
155 n as f64
156 } else if let Some(n) = value.as_u64() {
157 n as f64
158 } else {
159 return Err(BaseError::ValidationFailed(
160 field_name.to_string(),
161 "Min 验证器只能用于数值类型".to_string(),
162 ));
163 };
164 if num < *min_val {
165 return Err(BaseError::ValidationFailed(
166 field_name.to_string(),
167 format!("数值不能小于 {},当前值: {}", min_val, num),
168 ));
169 }
170 Ok(())
171 }
172
173 Validator::Max(max_val) => {
174 let num = if let Some(n) = value.as_f64() {
175 n
176 } else if let Some(n) = value.as_i64() {
177 n as f64
178 } else if let Some(n) = value.as_u64() {
179 n as f64
180 } else {
181 return Err(BaseError::ValidationFailed(
182 field_name.to_string(),
183 "Max 验证器只能用于数值类型".to_string(),
184 ));
185 };
186 if num > *max_val {
187 return Err(BaseError::ValidationFailed(
188 field_name.to_string(),
189 format!("数值不能大于 {},当前值: {}", max_val, num),
190 ));
191 }
192 Ok(())
193 }
194
195 #[cfg(feature = "validator")]
197 Validator::Email => {
198 if let Some(s) = value.as_str() {
199 if !email_regex().is_match(s) {
200 return Err(BaseError::ValidationFailed(
201 field_name.to_string(),
202 "邮箱格式无效,请使用标准邮箱格式(如 user@example.com)".to_string(),
203 ));
204 }
205 Ok(())
206 } else {
207 Err(BaseError::ValidationFailed(
208 field_name.to_string(),
209 "Email 验证器只能用于字符串类型".to_string(),
210 ))
211 }
212 }
213
214 #[cfg(not(feature = "validator"))]
216 Validator::Email => {
217 if let Some(s) = value.as_str() {
218 if !s.contains('@') {
219 return Err(BaseError::ValidationFailed(
220 field_name.to_string(),
221 "邮箱格式无效,必须包含 @ 符号".to_string(),
222 ));
223 }
224 Ok(())
225 } else {
226 Err(BaseError::ValidationFailed(
227 field_name.to_string(),
228 "Email 验证器只能用于字符串类型".to_string(),
229 ))
230 }
231 }
232
233 Validator::EmailLoose => {
235 if let Some(s) = value.as_str() {
236 if !s.contains('@') {
237 return Err(BaseError::ValidationFailed(
238 field_name.to_string(),
239 "邮箱格式无效,必须包含 @ 符号".to_string(),
240 ));
241 }
242 Ok(())
243 } else {
244 Err(BaseError::ValidationFailed(
245 field_name.to_string(),
246 "EmailLoose 验证器只能用于字符串类型".to_string(),
247 ))
248 }
249 }
250
251 #[cfg(feature = "validator")]
253 Validator::Phone => {
254 if let Some(s) = value.as_str() {
255 if !phone_regex().is_match(s) {
256 return Err(BaseError::ValidationFailed(
257 field_name.to_string(),
258 "手机号格式无效,请使用 E.164 格式(如 +8613800138000 或 13800138000)"
259 .to_string(),
260 ));
261 }
262 Ok(())
263 } else {
264 Err(BaseError::ValidationFailed(
265 field_name.to_string(),
266 "Phone 验证器只能用于字符串类型".to_string(),
267 ))
268 }
269 }
270
271 #[cfg(not(feature = "validator"))]
273 Validator::Phone => {
274 if let Some(s) = value.as_str() {
275 if !s
276 .chars()
277 .all(|c| c.is_ascii_digit() || c == '-' || c == '+')
278 {
279 return Err(BaseError::ValidationFailed(
280 field_name.to_string(),
281 "手机号格式无效,只能包含数字、连字符和加号".to_string(),
282 ));
283 }
284 Ok(())
285 } else {
286 Err(BaseError::ValidationFailed(
287 field_name.to_string(),
288 "Phone 验证器只能用于字符串类型".to_string(),
289 ))
290 }
291 }
292
293 Validator::PhoneLoose => {
295 if let Some(s) = value.as_str() {
296 if !s.chars().all(|c| c.is_ascii_digit() || c == '-') {
297 return Err(BaseError::ValidationFailed(
298 field_name.to_string(),
299 "手机号格式无效,只能包含数字和连字符".to_string(),
300 ));
301 }
302 Ok(())
303 } else {
304 Err(BaseError::ValidationFailed(
305 field_name.to_string(),
306 "PhoneLoose 验证器只能用于字符串类型".to_string(),
307 ))
308 }
309 }
310
311 Validator::Url => {
313 if let Some(s) = value.as_str() {
314 if !s.starts_with("http://") && !s.starts_with("https://") {
315 return Err(BaseError::ValidationFailed(
316 field_name.to_string(),
317 "URL 格式无效,必须以 http:// 或 https:// 开头".to_string(),
318 ));
319 }
320 Ok(())
321 } else {
322 Err(BaseError::ValidationFailed(
323 field_name.to_string(),
324 "Url 验证器只能用于字符串类型".to_string(),
325 ))
326 }
327 }
328
329 #[cfg(feature = "validator")]
331 Validator::Regex(pattern) => {
332 if let Some(s) = value.as_str() {
333 let cache = REGEX_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
334 {
336 let read_guard = cache.read().unwrap_or_else(|p| p.into_inner());
337 if let Some(re) = read_guard.get(pattern) {
338 return if re.is_match(s) {
339 Ok(())
340 } else {
341 Err(BaseError::ValidationFailed(
342 field_name.to_string(),
343 format!("值不匹配正则表达式: {}", pattern),
344 ))
345 };
346 }
347 }
348 let re = Regex::new(pattern).map_err(|e| {
350 BaseError::ValidationFailed(
351 field_name.to_string(),
352 format!("正则表达式无效: {}", e),
353 )
354 })?;
355 let mut write_guard = cache.write().unwrap_or_else(|p| p.into_inner());
356 let cached = write_guard.entry(pattern.to_string()).or_insert_with(|| re);
357 if cached.is_match(s) {
358 Ok(())
359 } else {
360 Err(BaseError::ValidationFailed(
361 field_name.to_string(),
362 format!("值不匹配正则表达式: {}", pattern),
363 ))
364 }
365 } else {
366 Err(BaseError::ValidationFailed(
367 field_name.to_string(),
368 "Regex 验证器只能用于字符串类型".to_string(),
369 ))
370 }
371 }
372
373 #[cfg(not(feature = "validator"))]
375 Validator::Regex(_pattern) => Err(BaseError::ValidationFailed(
376 field_name.to_string(),
377 "正则验证器需要启用 'validator' feature".to_string(),
378 )),
379
380 Validator::Custom(func) => func(field_name, value),
382 }
383 }
384}
385
386impl std::fmt::Debug for Validator {
388 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
389 match self {
390 Validator::MinLength(len) => write!(f, "MinLength({})", len),
391 Validator::MaxLength(len) => write!(f, "MaxLength({})", len),
392 Validator::Min(val) => write!(f, "Min({})", val),
393 Validator::Max(val) => write!(f, "Max({})", val),
394 Validator::Email => write!(f, "Email"),
395 Validator::EmailLoose => write!(f, "EmailLoose"),
396 Validator::Phone => write!(f, "Phone"),
397 Validator::PhoneLoose => write!(f, "PhoneLoose"),
398 Validator::Url => write!(f, "Url"),
399 Validator::Regex(pattern) => write!(f, "Regex(\"{}\")", pattern),
400 Validator::Custom(_) => write!(f, "Custom(<function>)"),
401 }
402 }
403}
404
405#[derive(Debug, Serialize, Deserialize)]
408#[serde(tag = "type", content = "value")]
409enum ValidatorSerde {
410 MinLength(usize),
411 MaxLength(usize),
412 Min(f64),
413 Max(f64),
414 Email,
415 EmailLoose,
416 Phone,
417 PhoneLoose,
418 Url,
419 Regex(String),
420}
421
422impl Serialize for Validator {
423 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
424 where
425 S: serde::Serializer,
426 {
427 let serde_variant = match self {
428 Validator::MinLength(len) => ValidatorSerde::MinLength(*len),
429 Validator::MaxLength(len) => ValidatorSerde::MaxLength(*len),
430 Validator::Min(val) => ValidatorSerde::Min(*val),
431 Validator::Max(val) => ValidatorSerde::Max(*val),
432 Validator::Email => ValidatorSerde::Email,
433 Validator::EmailLoose => ValidatorSerde::EmailLoose,
434 Validator::Phone => ValidatorSerde::Phone,
435 Validator::PhoneLoose => ValidatorSerde::PhoneLoose,
436 Validator::Url => ValidatorSerde::Url,
437 Validator::Regex(pattern) => ValidatorSerde::Regex(pattern.clone()),
438 Validator::Custom(_) => {
439 return Err(serde::ser::Error::custom("Custom 验证器无法序列化"));
440 }
441 };
442 serde_variant.serialize(serializer)
443 }
444}
445
446impl<'de> Deserialize<'de> for Validator {
447 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
448 where
449 D: serde::Deserializer<'de>,
450 {
451 let serde_variant = ValidatorSerde::deserialize(deserializer)?;
452 Ok(match serde_variant {
453 ValidatorSerde::MinLength(len) => Validator::MinLength(len),
454 ValidatorSerde::MaxLength(len) => Validator::MaxLength(len),
455 ValidatorSerde::Min(val) => Validator::Min(val),
456 ValidatorSerde::Max(val) => Validator::Max(val),
457 ValidatorSerde::Email => Validator::Email,
458 ValidatorSerde::EmailLoose => Validator::EmailLoose,
459 ValidatorSerde::Phone => Validator::Phone,
460 ValidatorSerde::PhoneLoose => Validator::PhoneLoose,
461 ValidatorSerde::Url => Validator::Url,
462 ValidatorSerde::Regex(pattern) => Validator::Regex(pattern),
463 })
464 }
465}