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