Expand description
Type-safe validation traits and immutable validator registries.
Use Validator for direct typed validation. Use a prepared adapter when
a domain rule must cross an erased input boundary. For configured execution,
declare ValidatorSignature values in a ValidatorDescriptor, register
the descriptor, then bind it into a reusable BoundValidator. Aggregate
bound results explicitly with ValidationReport when a caller needs a
report; this crate does not schedule rules.
A prepared validator is a lower-level entry point. Direct callers must provide a context that satisfies its declared dependency contract; bound execution performs the input and dependency checks before invoking it.
§Direct typed validation
use std::fmt;
use qubit_validator::Validator;
struct Positive;
#[derive(Debug)]
struct NotPositive;
impl fmt::Display for NotPositive {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("value must be positive")
}
}
impl std::error::Error for NotPositive {}
impl Validator<i32> for Positive {
type Error = NotPositive;
fn validate(&self, value: &i32, _: &()) -> Result<(), Self::Error> {
if *value > 0 { Ok(()) } else { Err(NotPositive) }
}
}
Positive.validate(&7, &()).unwrap();
assert!(Positive.validate(&0, &()).is_err());§Configured validation and reporting
use std::sync::Arc;
use qubit_validator::{
ArgumentReader, BindError, BoundValidationContext, InputType,
PreparedValidator, RegistrationSource, ValidationOutcome, ValidationPath,
ValidationReport, ValidationValue, Validator, ValidatorDescriptor, ValidatorId,
ValidatorRegistration, ValidatorRegistry, ValidatorSignature, ViolationCode,
prepare_text_validator,
};
struct NonBlank;
#[derive(Debug)]
struct Blank;
impl std::fmt::Display for Blank {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("blank name")
}
}
impl std::error::Error for Blank {}
impl Validator<str> for NonBlank {
type Error = Blank;
fn validate(&self, value: &str, _: &()) -> Result<(), Self::Error> {
if value.trim().is_empty() { Err(Blank) } else { Ok(()) }
}
}
fn prepare(_reader: &mut ArgumentReader<'_>) -> Result<Arc<dyn PreparedValidator>, BindError> {
Ok(prepare_text_validator(NonBlank, |_| {
qubit_validator::ViolationDraft::new(qubit_validator::ViolationCode::new("text.blank"))
}))
}
static SIGNATURES: &[ValidatorSignature] = &[ValidatorSignature::new(InputType::Text, &[], prepare)];
static DESCRIPTOR: ValidatorDescriptor = ValidatorDescriptor::new(SIGNATURES);
static REGISTRATION: ValidatorRegistration = ValidatorRegistration::new(
ValidatorId::new("profile.name.non_blank"),
&DESCRIPTOR,
RegistrationSource::new("profile-rules", "profile", "rules.rs", 1),
);
let registry = ValidatorRegistry::from_registrations([®ISTRATION])?;
let rule = registry.bind("profile.name.non_blank", InputType::Text, &[])?;
let outcome = rule.validate(
ValidationValue::Text("Ada"),
&BoundValidationContext::new(&[]),
)?;
let mut report = ValidationReport::new();
report.record_outcome(0, ValidationPath::root().with_field("name"), outcome)?;
assert!(report.is_valid());
let invalid = rule.validate(
ValidationValue::Text(" "),
&BoundValidationContext::new(&[]),
)?;
assert!(matches!(invalid, ValidationOutcome::Invalid(_)));
report.record_outcome(
1,
ValidationPath::root().with_field("name"),
invalid,
)?;
assert!(!report.is_valid());
assert_eq!(report.violations()[0].code(), ViolationCode::new("text.blank"));Macros§
- register_
validator - Registers a static typed validator descriptor in the optional global registry.
Structs§
- Argument
Reader - Reads declared arguments exactly once while rejecting duplicates, unknown names, and lossy numeric conversions.
- Bind
Error - A binding error that does not retain raw parameter values.
- Bound
Validation Context - Borrowed dependency slots used during a synchronous validation call.
- Bound
Validator - A bound occurrence that owns a reusable prepared validator instance.
- Dependency
Spec - Describes one ordered dependency slot supplied to a validator.
- Execution
Error - An execution error with a safe public diagnostic surface.
- Failure
Id - Identifies one retained failure within its originating report.
- Named
Validation Argument - One named validator parameter.
- Named
Validation Dependency - One dependency value identified by its signature name.
- Recorded
Outcome - Describes whether an outcome fit the report limits and identifies its retained failures.
- Registration
Source - Source location for one linked registration.
- Skipped
Validation - One validation occurrence that was skipped by the executor.
- Validation
Limits - Explicit bounds applied while collecting a validation report.
- Validation
Path - A structured path to a value being validated.
- Validation
Report - A bounded collection of validation violations and skipped occurrences.
- Validator
Descriptor - A definition containing one or more input/dependency signatures.
- Validator
Id - A validated, process-independent validator identifier.
- Validator
Registration - One validator definition associated with a stable identifier.
- Validator
Registry - A deterministic local registry containing one definition per stable ID.
- Validator
Signature - One statically declared way to bind a validator.
- Violation
- One rule violation without the rejected value.
- Violation
Code - A stable violation code using the point-separated ASCII protocol.
- Violation
Draft - A structured violation draft without a rule identity.
Enums§
- Bind
Error Kind - A configuration or declaration error found while binding a rule.
- Execution
Error Kind - A failure in the validation execution infrastructure.
- Input
Type - The two intentionally small input views used by the validation boundary.
- Path
Segment - One location segment in a validation path.
- Prepared
Outcome - The type-erased result produced before rule identity is attached.
- Skip
Reason - Why a rule did not run.
- Validation
Argument - One statically typed validator parameter value.
- Validation
Outcome - The observable result of executing one bound validator occurrence.
- Validation
Outcome Error - An outcome violates the invariant required by its declared variant.
- Validation
Value - A value view that deliberately avoids implicit stringification and cloning.
- Validator
IdError - A stable validator ID protocol violation.
- Validator
Registry Error - Failure while freezing a validator registry.
- Violation
Code Error - The reason a candidate string violates the stable violation-code protocol.
- Violation
Param - A restricted vocabulary for diagnostic parameters. The type limits how a value is represented; it cannot prove where the value came from. Callers must supply only program-declared tokens or rule configuration values, never rejected input or sensitive values derived from it.
Traits§
- Prepared
Validator - A configured, immutable validator instance safe to share between calls.
- Validator
- Validates a borrowed value using an immutable, typed context.
Functions§
- prepare_
contextual_ text_ validator - Prepares a text validator that reads its declared dependency slots.
- prepare_
contextual_ typed_ validator - Prepares a typed validator that reads its declared dependency slots.
- prepare_
text_ domain_ rule - Prepares a text domain validator with dependency context and error mapping.
- prepare_
text_ validator - Prepares a text validator using a domain-error mapper.
- prepare_
text_ with_ context - Prepares a text validation closure that receives its checked dependency context.
- prepare_
typed_ domain_ rule - Prepares a typed domain validator with dependency context and error mapping.
- prepare_
typed_ validator - Prepares a typed validator using a domain-error mapper.
- prepare_
typed_ with_ context - Prepares a typed validation closure that receives its checked dependency context.
Type Aliases§
- Prepare
Fn - Constructs an owned prepared validator from declaration parameters.