rustapi_validate/lib.rs
1//! # RustAPI Validation
2//!
3//! Validation system for RustAPI framework. Provides declarative validation
4//! on structs using the `#[derive(Validate)]` macro.
5//!
6//! ## Example
7//!
8//! ```rust,ignore
9//! use rustapi_validate::prelude::*;
10//! use validator::Validate;
11//!
12//! #[derive(Validate)]
13//! struct CreateUser {
14//! #[validate(email)]
15//! email: String,
16//!
17//! #[validate(length(min = 3, max = 50))]
18//! username: String,
19//!
20//! #[validate(range(min = 18, max = 120))]
21//! age: u8,
22//! }
23//! ```
24//!
25//! ## Validation Rules
26//!
27//! - `email` - Validates email format
28//! - `length(min = X, max = Y)` - String length validation
29//! - `range(min = X, max = Y)` - Numeric range validation
30//! - `regex = "..."` - Regex pattern validation
31//! - `non_empty` - Non-empty string/collection validation
32//! - `nested` - Validates nested structs
33//!
34//! ## Error Format
35//!
36//! Validation errors return a 422 Unprocessable Entity with JSON:
37//!
38//! ```json
39//! {
40//! "error": {
41//! "type": "validation_error",
42//! "message": "Validation failed",
43//! "fields": [
44//! {"field": "email", "code": "email", "message": "Invalid email format"},
45//! {"field": "age", "code": "range", "message": "Value must be between 18 and 120"}
46//! ]
47//! }
48//! }
49//! ```
50
51mod error;
52mod validate;
53
54pub use error::{FieldError, ValidationError};
55pub use validate::Validate;
56
57// Re-export the derive macro from validator (wrapped)
58// In a full implementation, we'd create our own proc-macro
59// For now, we use validator's derive with our own trait
60pub use validator::Validate as ValidatorValidate;
61
62/// Prelude module for validation
63pub mod prelude {
64 pub use crate::error::{FieldError, ValidationError};
65 pub use crate::validate::Validate;
66 pub use validator::Validate as ValidatorValidate;
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn validation_error_to_json() {
75 let error = ValidationError::new(vec![
76 FieldError::new("email", "email", "Invalid email format"),
77 FieldError::new("age", "range", "Value must be between 18 and 120"),
78 ]);
79
80 let json = serde_json::to_string_pretty(&error).unwrap();
81 assert!(json.contains("validation_error"));
82 assert!(json.contains("email"));
83 assert!(json.contains("age"));
84 }
85}