Skip to main content

Validator

Trait Validator 

Source
pub trait Validator<T: ?Sized, C: ?Sized = ()> {
    type Error: Error + 'static;

    // Required method
    fn validate(&self, value: &T, context: &C) -> Result<(), Self::Error>;
}
Expand description

Validates a borrowed value using an immutable, typed context.

§Examples

use std::fmt;

use qubit_validator::Validator;

#[derive(Debug, Eq, PartialEq)]
struct EmptyText;

impl fmt::Display for EmptyText {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("text must not be empty")
    }
}

impl std::error::Error for EmptyText {}

struct NonEmpty;

impl Validator<str> for NonEmpty {
    type Error = EmptyText;

    fn validate(&self, value: &str, _: &()) -> Result<(), Self::Error> {
        if value.is_empty() { Err(EmptyText) } else { Ok(()) }
    }
}

assert!(NonEmpty.validate("ready", &()).is_ok());
assert_eq!(NonEmpty.validate("", &()).unwrap_err(), EmptyText);

§Type Parameters

  • T: Borrowed value type accepted by the validator.
  • C: Immutable context supplied for each validation call.

Required Associated Types§

Source

type Error: Error + 'static

The domain error returned when the value is invalid.

Required Methods§

Source

fn validate(&self, value: &T, context: &C) -> Result<(), Self::Error>

Validates value with context.

§Parameters
  • value: The borrowed value to validate.
  • context: Immutable domain context for this call.
§Errors

Returns the validator-specific error when the value is invalid.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§