StringSchema

Struct StringSchema 

Source
pub struct StringSchema { /* private fields */ }
Expand description

A schema for validating string values.

StringSchema validates that values are strings and optionally applies constraints like minimum/maximum length and regex patterns. All constraint violations are accumulated rather than short-circuiting on the first failure.

§Example

use postmortem::{Schema, JsonPath};
use serde_json::json;

// Create schema with multiple constraints
let schema = Schema::string()
    .min_len(3)
    .max_len(20)
    .pattern(r"^[a-z]+$")
    .unwrap();

// Validation accumulates all errors
let result = schema.validate(&json!("AB"), &JsonPath::root());
assert!(result.is_failure());
// Will report both: too short AND pattern mismatch

Implementations§

Source§

impl StringSchema

Source

pub fn new() -> Self

Creates a new string schema with no constraints.

Source

pub fn min_len(self, min: usize) -> Self

Adds a minimum length constraint.

The string must have at least min characters (Unicode scalar values).

§Example
use postmortem::{Schema, JsonPath};
use serde_json::json;

let schema = Schema::string().min_len(5);

let result = schema.validate(&json!("hello"), &JsonPath::root());
assert!(result.is_success());

let result = schema.validate(&json!("hi"), &JsonPath::root());
assert!(result.is_failure());
Source

pub fn max_len(self, max: usize) -> Self

Adds a maximum length constraint.

The string must have at most max characters (Unicode scalar values).

§Example
use postmortem::{Schema, JsonPath};
use serde_json::json;

let schema = Schema::string().max_len(10);

let result = schema.validate(&json!("hello"), &JsonPath::root());
assert!(result.is_success());

let result = schema.validate(&json!("this is too long"), &JsonPath::root());
assert!(result.is_failure());
Source

pub fn pattern(self, pattern: &str) -> Result<Self, Error>

Adds a regex pattern constraint.

The string must match the provided regex pattern. Returns an error if the regex pattern is invalid.

§Example
use postmortem::{Schema, JsonPath};
use serde_json::json;

let schema = Schema::string()
    .pattern(r"^\d+$")
    .unwrap();

let result = schema.validate(&json!("12345"), &JsonPath::root());
assert!(result.is_success());

let result = schema.validate(&json!("abc"), &JsonPath::root());
assert!(result.is_failure());
Source

pub fn email(self) -> Self

Adds an email format constraint.

Source

pub fn url(self) -> Self

Adds a URL format constraint (http/https).

Source

pub fn uuid(self) -> Self

Adds a UUID format constraint.

Source

pub fn date(self) -> Self

Adds a date format constraint (YYYY-MM-DD).

Source

pub fn datetime(self) -> Self

Adds a datetime format constraint (ISO 8601).

Source

pub fn ip(self) -> Self

Adds an IP address format constraint (IPv4 or IPv6).

Source

pub fn ipv4(self) -> Self

Adds an IPv4 format constraint.

Source

pub fn ipv6(self) -> Self

Adds an IPv6 format constraint.

Source

pub fn one_of<I, S>(self, values: I) -> Self
where I: IntoIterator<Item = S>, S: Into<String>,

Adds an enumeration constraint.

Source

pub fn starts_with(self, prefix: impl Into<String>) -> Self

Adds a starts-with constraint.

Source

pub fn ends_with(self, suffix: impl Into<String>) -> Self

Adds an ends-with constraint.

Source

pub fn contains(self, substring: impl Into<String>) -> Self

Adds a contains constraint.

Source

pub fn trim(self) -> Self

Adds a trim transformation.

Source

pub fn lowercase(self) -> Self

Adds a lowercase transformation.

Source

pub fn custom<F>(self, validator: F) -> Self
where F: Fn(&str, &JsonPath) -> Validation<(), SchemaErrors> + Send + Sync + 'static,

Adds a custom validator.

Source

pub fn error(self, message: impl Into<String>) -> Self

Sets a custom error message for the most recent constraint.

If no constraints have been added yet, this sets the type error message (used when the value is not a string).

§Example
use postmortem::{Schema, JsonPath};
use serde_json::json;

let schema = Schema::string()
    .min_len(5)
    .error("username must be at least 5 characters");

let result = schema.validate(&json!("hi"), &JsonPath::root());
// Error message will be "username must be at least 5 characters"
Source

pub fn validate( &self, value: &Value, path: &JsonPath, ) -> Validation<String, SchemaErrors>

Validates a value against this schema.

Returns Validation::Success with the validated string if all constraints pass, or Validation::Failure with all accumulated errors if any constraints fail.

§Example
use postmortem::{Schema, JsonPath};
use serde_json::json;

let schema = Schema::string().min_len(1).max_len(10);

match schema.validate(&json!("hello"), &JsonPath::root()) {
    stillwater::Validation::Success(s) => println!("Valid: {}", s),
    stillwater::Validation::Failure(errors) => {
        for error in errors.iter() {
            println!("Error: {}", error);
        }
    }
}

Trait Implementations§

Source§

impl Clone for StringSchema

Source§

fn clone(&self) -> StringSchema

Returns a duplicate of the value. Read more
1.0.0§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for StringSchema

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl SchemaLike for StringSchema

Source§

type Output = String

The output type produced by successful validation.
Source§

fn validate( &self, value: &Value, path: &JsonPath, ) -> Validation<Self::Output, SchemaErrors>

Validates a value against this schema. Read more
Source§

fn validate_to_value( &self, value: &Value, path: &JsonPath, ) -> Validation<Value, SchemaErrors>

Validates a value and returns the result as a serde_json::Value. Read more
Source§

fn validate_with_context( &self, value: &Value, path: &JsonPath, _context: &ValidationContext, ) -> Validation<Self::Output, SchemaErrors>

Validates a value with registry context for schema reference resolution. Read more
Source§

fn validate_to_value_with_context( &self, value: &Value, path: &JsonPath, _context: &ValidationContext, ) -> Validation<Value, SchemaErrors>

Validates a value with context and returns the result as a serde_json::Value. Read more
Source§

fn collect_refs(&self, _refs: &mut Vec<String>)

Collects all schema reference names used by this schema. Read more
Source§

impl ToJsonSchema for StringSchema

Source§

fn to_json_schema(&self) -> Value

Converts this schema to a JSON Schema representation. Read more

Auto Trait Implementations§

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CloneToUninit for T
where T: Clone,

§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S> ValueValidator for S

Source§

fn validate_value( &self, value: &Value, path: &JsonPath, ) -> Validation<Value, SchemaErrors>

Validates a value and returns the result as a serde_json::Value.
Source§

fn validate_value_with_context( &self, value: &Value, path: &JsonPath, context: &ValidationContext, ) -> Validation<Value, SchemaErrors>

Validates a value with context and returns the result as a serde_json::Value. Read more
Source§

fn collect_refs(&self, refs: &mut Vec<String>)

Collects schema reference names. Read more
Source§

fn to_json_schema(&self) -> Value

Converts this schema to JSON Schema format. Read more