Skip to main content

karbon_framework/validation/constraints/
mod.rs

1pub mod collection;
2pub mod comparison;
3pub mod date;
4pub mod number;
5pub mod security;
6pub mod string;
7
8/// Result type for constraint validation
9pub type ConstraintResult = Result<(), ConstraintViolation>;
10
11/// Represents a validation constraint violation
12#[derive(Debug, Clone)]
13pub struct ConstraintViolation {
14    pub constraint: &'static str,
15    pub message: String,
16    pub invalid_value: String,
17}
18
19impl ConstraintViolation {
20    pub fn new(constraint: &'static str, message: impl Into<String>, invalid_value: impl Into<String>) -> Self {
21        Self {
22            constraint,
23            message: message.into(),
24            invalid_value: invalid_value.into(),
25        }
26    }
27}
28
29impl std::fmt::Display for ConstraintViolation {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        write!(f, "[{}] {}", self.constraint, self.message)
32    }
33}
34
35impl std::error::Error for ConstraintViolation {}
36
37/// Trait for all validation constraints operating on string values
38pub trait Constraint {
39    fn validate(&self, value: &str) -> ConstraintResult;
40    fn name(&self) -> &'static str;
41}
42
43/// Trait for validation constraints operating on numeric values
44pub trait NumericConstraint {
45    fn validate_f64(&self, value: f64) -> ConstraintResult;
46    fn name(&self) -> &'static str;
47}
48
49/// Trait for validation constraints operating on collections
50pub trait CollectionConstraint {
51    fn validate_slice<T>(&self, value: &[T]) -> ConstraintResult;
52    fn name(&self) -> &'static str;
53}
54
55// Re-export all constraints
56pub use collection::*;
57pub use comparison::*;
58pub use date::*;
59pub use number::*;
60pub use security::*;
61pub use string::*;