1use regex::Regex;
2use std::net::ToSocketAddrs;
3use std::sync::Arc;
4
5use super::dns::dns_lookups_faked;
6
7#[derive(Debug, Clone)]
9pub struct ValidationError(pub String);
10
11impl ValidationError {
12 pub fn new(message: impl Into<String>) -> Self {
13 Self(message.into())
14 }
15}
16
17impl std::fmt::Display for ValidationError {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19 write!(f, "{}", self.0)
20 }
21}
22
23impl std::error::Error for ValidationError {}
24
25pub trait ValidationRule: Send + Sync + std::fmt::Debug {
27 fn name(&self) -> &str;
29 fn validate(&self, field: &str, value: &str) -> Result<(), ValidationError>;
31}
32
33#[derive(Clone)]
34pub enum Rule {
35 Required,
36 Email,
37 Min(usize),
38 Max(usize),
39 MinValue(f64),
40 MaxValue(f64),
41 String,
42 Numeric,
43 Boolean,
44 Confirmed,
45 Same(String),
46 Different(String),
47 Alpha,
48 AlphaNumeric,
49 Url,
50 ActiveUrl,
53 EmailDns,
56 Ip,
57 Base64,
58 Regex(Regex),
59 Between(usize, usize),
60 Size(usize),
61 Present,
62 Prohibited,
63 Custom(Arc<dyn ValidationRule>),
64 Unique(UniqueRule),
67 Exists(ExistsRule),
70}
71
72#[derive(Clone, Debug)]
82pub struct UniqueRule {
83 pub table: String,
84 pub column: Option<String>,
86 pub ignore_id: Option<String>,
88}
89
90#[derive(Clone, Debug)]
92pub struct ExistsRule {
93 pub table: String,
94 pub column: Option<String>,
96}
97
98impl std::fmt::Debug for Rule {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 match self {
101 Self::Required => write!(f, "Required"),
102 Self::Email => write!(f, "Email"),
103 Self::Min(n) => write!(f, "Min({})", n),
104 Self::Max(n) => write!(f, "Max({})", n),
105 Self::MinValue(n) => write!(f, "MinValue({})", n),
106 Self::MaxValue(n) => write!(f, "MaxValue({})", n),
107 Self::String => write!(f, "String"),
108 Self::Numeric => write!(f, "Numeric"),
109 Self::Boolean => write!(f, "Boolean"),
110 Self::Confirmed => write!(f, "Confirmed"),
111 Self::Same(s) => write!(f, "Same({})", s),
112 Self::Different(s) => write!(f, "Different({})", s),
113 Self::Alpha => write!(f, "Alpha"),
114 Self::AlphaNumeric => write!(f, "AlphaNumeric"),
115 Self::Url => write!(f, "Url"),
116 Self::ActiveUrl => write!(f, "ActiveUrl"),
117 Self::EmailDns => write!(f, "EmailDns"),
118 Self::Ip => write!(f, "Ip"),
119 Self::Base64 => write!(f, "Base64"),
120 Self::Regex(_) => write!(f, "Regex"),
121 Self::Between(a, b) => write!(f, "Between({}, {})", a, b),
122 Self::Size(n) => write!(f, "Size({})", n),
123 Self::Present => write!(f, "Present"),
124 Self::Prohibited => write!(f, "Prohibited"),
125 Self::Unique(r) => write!(
126 f,
127 "Unique({}.{})",
128 r.table,
129 r.column.as_deref().unwrap_or("*")
130 ),
131 Self::Exists(r) => write!(
132 f,
133 "Exists({}.{})",
134 r.table,
135 r.column.as_deref().unwrap_or("*")
136 ),
137 Self::Custom(rule) => write!(f, "Custom({})", rule.name()),
138 }
139 }
140}
141
142pub fn required() -> Rule {
143 Rule::Required
144}
145pub fn email() -> Rule {
146 Rule::Email
147}
148pub fn email_dns() -> Rule {
154 Rule::EmailDns
155}
156pub fn min(n: usize) -> Rule {
157 Rule::Min(n)
158}
159pub fn max(n: usize) -> Rule {
160 Rule::Max(n)
161}
162pub fn min_value(n: f64) -> Rule {
163 Rule::MinValue(n)
164}
165pub fn max_value(n: f64) -> Rule {
166 Rule::MaxValue(n)
167}
168pub fn string() -> Rule {
169 Rule::String
170}
171pub fn numeric() -> Rule {
172 Rule::Numeric
173}
174pub fn boolean() -> Rule {
175 Rule::Boolean
176}
177pub fn confirmed() -> Rule {
178 Rule::Confirmed
179}
180pub fn same(field: &str) -> Rule {
181 Rule::Same(field.to_string())
182}
183pub fn different(field: &str) -> Rule {
184 Rule::Different(field.to_string())
185}
186pub fn alpha() -> Rule {
187 Rule::Alpha
188}
189pub fn alpha_numeric() -> Rule {
190 Rule::AlphaNumeric
191}
192pub fn url() -> Rule {
193 Rule::Url
194}
195pub fn active_url() -> Rule {
201 Rule::ActiveUrl
202}
203pub fn ip() -> Rule {
204 Rule::Ip
205}
206
207pub fn base64() -> Rule {
210 Rule::Base64
211}
212pub fn regex(pattern: &str) -> Result<Rule, regex::Error> {
213 Regex::new(pattern).map(Rule::Regex)
214}
215pub fn between(min: usize, max: usize) -> Rule {
216 Rule::Between(min, max)
217}
218pub fn size(n: usize) -> Rule {
219 Rule::Size(n)
220}
221pub fn present() -> Rule {
222 Rule::Present
223}
224pub fn prohibited() -> Rule {
225 Rule::Prohibited
226}
227
228pub fn unique(table: &str, column: Option<&str>) -> Rule {
236 Rule::Unique(UniqueRule {
237 table: table.to_string(),
238 column: column.map(|c| c.to_string()),
239 ignore_id: None,
240 })
241}
242
243pub fn unique_except(table: &str, column: Option<&str>, ignore_id: &str) -> Rule {
246 Rule::Unique(UniqueRule {
247 table: table.to_string(),
248 column: column.map(|c| c.to_string()),
249 ignore_id: Some(ignore_id.to_string()),
250 })
251}
252
253pub fn exists(table: &str, column: Option<&str>) -> Rule {
257 Rule::Exists(ExistsRule {
258 table: table.to_string(),
259 column: column.map(|c| c.to_string()),
260 })
261}
262
263pub fn custom(rule: Arc<dyn ValidationRule>) -> Rule {
264 Rule::Custom(rule)
265}
266
267pub(crate) fn check_rule(
268 rule: &Rule,
269 field: &str,
270 value: Option<&serde_json::Value>,
271 all_data: &std::collections::HashMap<String, serde_json::Value>,
272) -> Option<String> {
273 match rule {
274 Rule::Required => match value {
275 None | Some(serde_json::Value::Null) => {
276 Some(format!("The {} field is required.", field))
277 }
278 Some(serde_json::Value::String(s)) if s.is_empty() => {
279 Some(format!("The {} field is required.", field))
280 }
281 _ => None,
282 },
283 Rule::Email => {
284 let s = value.and_then(|v| v.as_str())?;
285 let email_regex =
286 Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").unwrap();
287 if !email_regex.is_match(s) {
288 return Some(format!("The {} must be a valid email address.", field));
289 }
290 None
291 }
292 Rule::EmailDns => {
293 let s = value.and_then(|v| v.as_str())?;
294 let email_regex =
295 Regex::new(r"^[a-zA-Z0-9._%+-]+@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$").unwrap();
296 let Some(caps) = email_regex.captures(s) else {
297 return Some(format!("The {} must be a valid email address.", field));
298 };
299 let domain = &caps[1];
300 if !dns_lookups_faked() {
301 let resolves = (domain, 25u16)
302 .to_socket_addrs()
303 .map(|mut addrs| addrs.next().is_some())
304 .unwrap_or(false);
305 if !resolves {
306 return Some(format!("The {} must be a valid email address.", field));
307 }
308 }
309 None
310 }
311 Rule::Min(n) => {
312 if let Some(s) = value.and_then(|v| v.as_str()) {
313 if s.len() < *n {
314 return Some(format!("The {} must be at least {} characters.", field, n));
315 }
316 }
317 None
318 }
319 Rule::Max(n) => {
320 if let Some(s) = value.and_then(|v| v.as_str()) {
321 if s.len() > *n {
322 return Some(format!("The {} must not exceed {} characters.", field, n));
323 }
324 }
325 None
326 }
327 Rule::MinValue(n) => {
328 if let Some(num) = value.and_then(|v| v.as_f64()) {
329 if num < *n {
330 return Some(format!("The {} must be at least {}.", field, n));
331 }
332 }
333 None
334 }
335 Rule::MaxValue(n) => {
336 if let Some(num) = value.and_then(|v| v.as_f64()) {
337 if num > *n {
338 return Some(format!("The {} must not exceed {}.", field, n));
339 }
340 }
341 None
342 }
343 Rule::String => {
344 if let Some(v) = value {
345 if !v.is_string() {
346 return Some(format!("The {} must be a string.", field));
347 }
348 }
349 None
350 }
351 Rule::Numeric => {
352 if let Some(v) = value {
353 if !v.is_number() {
354 return Some(format!("The {} must be a number.", field));
355 }
356 }
357 None
358 }
359 Rule::Boolean => {
360 if let Some(v) = value {
361 match v {
362 serde_json::Value::Bool(_) => {}
363 serde_json::Value::String(s)
364 if s == "true" || s == "false" || s == "1" || s == "0" => {}
365 serde_json::Value::Number(n)
366 if n.as_f64() == Some(1.0) || n.as_f64() == Some(0.0) => {}
367 _ => return Some(format!("The {} field must be true or false.", field)),
368 }
369 }
370 None
371 }
372 Rule::Confirmed => {
373 let confirmation = format!("{}_confirmation", field);
374 let val = value.and_then(|v| v.as_str());
375 let conf = all_data.get(&confirmation).and_then(|v| v.as_str());
376 match (val, conf) {
377 (Some(v), Some(c)) if v == c => None,
378 _ => Some(format!("The {} confirmation does not match.", field)),
379 }
380 }
381 Rule::Same(other) => {
382 let val = value.and_then(|v| v.as_str());
383 let other_val = all_data.get(other).and_then(|v| v.as_str());
384 match (val, other_val) {
385 (Some(v), Some(o)) if v == o => None,
386 _ => Some(format!("The {} and {} must match.", field, other)),
387 }
388 }
389 Rule::Different(other) => {
390 let val = value.and_then(|v| v.as_str());
391 let other_val = all_data.get(other).and_then(|v| v.as_str());
392 match (val, other_val) {
393 (Some(v), Some(o)) if v != o => None,
394 _ => Some(format!("The {} and {} must be different.", field, other)),
395 }
396 }
397 Rule::Alpha => {
398 if let Some(s) = value.and_then(|v| v.as_str()) {
399 if !s.chars().all(|c| c.is_ascii_alphabetic()) {
400 return Some(format!("The {} must contain only letters.", field));
401 }
402 }
403 None
404 }
405 Rule::AlphaNumeric => {
406 if let Some(s) = value.and_then(|v| v.as_str()) {
407 if !s.chars().all(|c| c.is_ascii_alphanumeric()) {
408 return Some(format!(
409 "The {} must contain only letters and numbers.",
410 field
411 ));
412 }
413 }
414 None
415 }
416 Rule::Url => {
417 if let Some(s) = value.and_then(|v| v.as_str()) {
418 if !s.starts_with("http://") && !s.starts_with("https://") {
419 return Some(format!("The {} must be a valid URL.", field));
420 }
421 }
422 None
423 }
424 Rule::ActiveUrl => {
425 if let Some(s) = value.and_then(|v| v.as_str()) {
426 if !s.starts_with("http://") && !s.starts_with("https://") {
427 return Some(format!("The {} must be a valid URL.", field));
428 }
429 if !dns_lookups_faked() {
430 let host = s
431 .split_once("://")
432 .and_then(|(_, rest)| rest.split(['/', '?', '#', ':']).next())
433 .unwrap_or("");
434 let resolves = !host.is_empty()
435 && (host, 80u16)
436 .to_socket_addrs()
437 .map(|mut addrs| addrs.next().is_some())
438 .unwrap_or(false);
439 if !resolves {
440 return Some(format!("The {} must be a valid URL.", field));
441 }
442 }
443 }
444 None
445 }
446 Rule::Ip => {
447 if let Some(s) = value.and_then(|v| v.as_str()) {
448 let ip_re = Regex::new(r"^(\d{1,3}\.){3}\d{1,3}$|^([0-9a-fA-F:]+)$").unwrap();
449 if !ip_re.is_match(s) {
450 return Some(format!("The {} must be a valid IP address.", field));
451 }
452 }
453 None
454 }
455 Rule::Base64 => {
456 if let Some(s) = value.and_then(|v| v.as_str()) {
457 use base64::Engine as _;
458 let valid = base64::engine::general_purpose::STANDARD
459 .decode(s.as_bytes())
460 .ok()
461 .map(|decoded| base64::engine::general_purpose::STANDARD.encode(decoded) == s)
462 .unwrap_or(false);
463 if !valid {
464 return Some(format!("The {} must be a valid base64 string.", field));
465 }
466 }
467 None
468 }
469 Rule::Regex(re) => {
470 if let Some(s) = value.and_then(|v| v.as_str()) {
471 if !re.is_match(s) {
472 return Some(format!("The {} format is invalid.", field));
473 }
474 }
475 None
476 }
477 Rule::Between(min, max) => {
478 if let Some(s) = value.and_then(|v| v.as_str()) {
479 if s.len() < *min || s.len() > *max {
480 return Some(format!(
481 "The {} must be between {} and {} characters.",
482 field, min, max
483 ));
484 }
485 }
486 None
487 }
488 Rule::Size(n) => {
489 if let Some(s) = value.and_then(|v| v.as_str()) {
490 if s.len() != *n {
491 return Some(format!("The {} must be exactly {} characters.", field, n));
492 }
493 }
494 None
495 }
496 Rule::Present => {
497 if value.is_none() {
498 return Some(format!("The {} field must be present.", field));
499 }
500 None
501 }
502 Rule::Prohibited => {
503 if value.is_some() && value != Some(&serde_json::Value::Null) {
504 return Some(format!("The {} field is prohibited.", field));
505 }
506 None
507 }
508 Rule::Custom(rule) => {
509 let val = value.and_then(|v| v.as_str()).unwrap_or("");
510 rule.validate(field, val).err().map(|e| e.0)
511 }
512 Rule::Unique(_) | Rule::Exists(_) => Some(format!(
513 "The {} field must be validated asynchronously (use validate_async).",
514 field
515 )),
516 }
517}
518
519pub(crate) async fn check_rule_async(
522 rule: &Rule,
523 field: &str,
524 value: Option<&serde_json::Value>,
525 all_data: &std::collections::HashMap<String, serde_json::Value>,
526 db: &sea_orm::DatabaseConnection,
527) -> Option<String> {
528 use sea_orm::{ConnectionTrait, DatabaseBackend, Statement};
529
530 match rule {
531 Rule::Unique(r) => {
532 let raw = value?;
533 let column = r.column.clone().unwrap_or_else(|| field.to_string());
534 let value_str = match raw {
535 serde_json::Value::String(s) => s.clone(),
536 other => other.to_string(),
537 };
538 let sql = match &r.ignore_id {
539 Some(_id) => format!(
540 "SELECT COUNT(*) FROM {} WHERE {} = ?1 AND id != ?2",
541 r.table, column
542 ),
543 None => format!("SELECT COUNT(*) FROM {} WHERE {} = ?1", r.table, column),
544 };
545 let mut values = vec![value_str.into()];
546 if let Some(id) = &r.ignore_id {
547 values.push(id.clone().into());
548 }
549 match db
550 .query_one(Statement::from_sql_and_values(
551 DatabaseBackend::Sqlite,
552 &sql,
553 values,
554 ))
555 .await
556 {
557 Ok(Some(row)) => {
558 let count: i64 = row.try_get_by_index(0).unwrap_or(0);
559 if count > 0 {
560 Some(format!("The {} has already been taken.", field))
561 } else {
562 None
563 }
564 }
565 Ok(None) => None,
566 Err(e) => Some(format!(
567 "The {} could not be validated against the database: {}",
568 field, e
569 )),
570 }
571 }
572 Rule::Exists(r) => {
573 let raw = value?;
574 let column = r.column.clone().unwrap_or_else(|| field.to_string());
575 let value_str = match raw {
576 serde_json::Value::String(s) => s.clone(),
577 other => other.to_string(),
578 };
579 let sql = format!("SELECT COUNT(*) FROM {} WHERE {} = ?1", r.table, column);
580 match db
581 .query_one(Statement::from_sql_and_values(
582 DatabaseBackend::Sqlite,
583 &sql,
584 [value_str.into()],
585 ))
586 .await
587 {
588 Ok(Some(row)) => {
589 let count: i64 = row.try_get_by_index(0).unwrap_or(0);
590 if count == 0 {
591 Some(format!("The selected {} is invalid.", field))
592 } else {
593 None
594 }
595 }
596 Ok(None) => None,
597 Err(e) => Some(format!(
598 "The {} could not be validated against the database: {}",
599 field, e
600 )),
601 }
602 }
603 _ => check_rule(rule, field, value, all_data),
604 }
605}