Struct ValidationOptions

Source
pub struct ValidationOptions<R = Arc<dyn Retrieve>> { /* private fields */ }
Expand description

Configuration options for JSON Schema validation.

Implementations§

Source§

impl<R> ValidationOptions<R>

Source

pub fn with_draft(self, draft: Draft) -> Self

Sets the JSON Schema draft version.

use jsonschema::Draft;

let options = jsonschema::options()
    .with_draft(Draft::Draft4);
Source

pub fn with_content_media_type( self, media_type: &'static str, media_type_check: fn(&str) -> bool, ) -> Self

Add support for a custom content media type validation.

§Example
fn check_custom_media_type(instance_string: &str) -> bool {
    instance_string.starts_with("custom:")
}

let options = jsonschema::options()
    .with_content_media_type("application/custom", check_custom_media_type);
Source

pub fn without_content_media_type_support( self, media_type: &'static str, ) -> Self

Remove support for a specific content media type validation.

Source

pub fn with_content_encoding( self, encoding: &'static str, check: fn(&str) -> bool, converter: fn(&str) -> Result<Option<String>, ValidationError<'static>>, ) -> Self

Add support for a custom content encoding.

§Arguments
  • encoding: Name of the content encoding (e.g., “base64”)
  • check: Validates the input string (return true if valid)
  • converter: Converts the input string, returning:
    • Err(ValidationError): For supported errors
    • Ok(None): If input is invalid
    • Ok(Some(content)): If valid, with decoded content
§Example
use jsonschema::ValidationError;

fn check(s: &str) -> bool {
    s.starts_with("valid:")
}

fn convert(s: &str) -> Result<Option<String>, ValidationError<'static>> {
    if s.starts_with("valid:") {
        Ok(Some(s[6..].to_string()))
    } else {
        Ok(None)
    }
}

let options = jsonschema::options()
    .with_content_encoding("custom", check, convert);
Source

pub fn without_content_encoding_support( self, content_encoding: &'static str, ) -> Self

Remove support for a specific content encoding.

§Example
let options = jsonschema::options()
    .without_content_encoding_support("base64");
Source

pub fn with_resource(self, uri: impl Into<String>, resource: Resource) -> Self

Add a custom schema, allowing it to be referenced by the specified URI during validation.

This enables the use of additional in-memory schemas alongside the main schema being validated.

§Example
use jsonschema::Resource;

let extra = Resource::from_contents(json!({"minimum": 5}))?;

let validator = jsonschema::options()
    .with_resource("urn:minimum-schema", extra)
    .build(&json!({"$ref": "urn:minimum-schema"}))?;
assert!(validator.is_valid(&json!(5)));
assert!(!validator.is_valid(&json!(4)));
Source

pub fn with_resources( self, pairs: impl Iterator<Item = (impl Into<String>, Resource)>, ) -> Self

Add custom schemas, allowing them to be referenced by the specified URI during validation.

This enables the use of additional in-memory schemas alongside the main schema being validated.

§Example
use jsonschema::Resource;

let validator = jsonschema::options()
    .with_resources([
        (
            "urn:minimum-schema",
            Resource::from_contents(json!({"minimum": 5}))?,
        ),
        (
            "urn:maximum-schema",
            Resource::from_contents(json!({"maximum": 10}))?,
        ),
      ].into_iter())
    .build(&json!({"$ref": "urn:minimum-schema"}))?;
assert!(validator.is_valid(&json!(5)));
assert!(!validator.is_valid(&json!(4)));
Source

pub fn with_registry(self, registry: Registry) -> Self

Use external schema resources from the registry, making them accessible via references during validation.

§Example
use jsonschema::{Registry, Resource};

let registry = Registry::try_new(
    "urn:name-schema",
    Resource::from_contents(json!({"type": "string"}))?
)?;
let schema = json!({
    "properties": {
        "name": { "$ref": "urn:name-schema" }
    }
});
let validator = jsonschema::options()
    .with_registry(registry)
    .build(&schema)?;
assert!(validator.is_valid(&json!({ "name": "Valid String" })));
assert!(!validator.is_valid(&json!({ "name": 123 })));
Source

pub fn with_format<N, F>(self, name: N, format: F) -> Self
where N: Into<String>, F: Fn(&str) -> bool + Send + Sync + 'static,

Register a custom format validator.

§Example
fn my_format(s: &str) -> bool {
   // Your awesome format check!
   s.ends_with("42!")
}
let schema = json!({"type": "string", "format": "custom"});
let validator = jsonschema::options()
    .with_format("custom", my_format)
    .build(&schema)
    .expect("Valid schema");

assert!(!validator.is_valid(&json!("foo")));
assert!(validator.is_valid(&json!("foo42!")));
Source

pub fn should_validate_formats(self, yes: bool) -> Self

Set whether to validate formats.

Default behavior depends on the draft version. This method overrides the default, enabling or disabling format validation regardless of draft.

Source

pub fn should_ignore_unknown_formats(self, yes: bool) -> Self

Set whether to ignore unknown formats.

By default, unknown formats are silently ignored. Set to false to report unrecognized formats as validation errors.

Source

pub fn with_keyword<N, F>(self, name: N, factory: F) -> Self
where N: Into<String>, F: for<'a> Fn(&'a Map<String, Value>, &'a Value, Location) -> Result<Box<dyn Keyword>, ValidationError<'a>> + Send + Sync + 'static,

Register a custom keyword validator.

§Example

struct MyCustomValidator;

impl Keyword for MyCustomValidator {
    fn validate<'i>(
        &self,
        instance: &'i Value,
        location: &LazyLocation,
    ) -> Result<(), ValidationError<'i>> {
        // ... validate instance ...
        if !instance.is_object() {
            return Err(ValidationError::custom(
                Location::new(),
                location.into(),
                instance,
                "Boom!",
            ));
        } else {
            Ok(())
        }
    }
    fn is_valid(&self, instance: &Value) -> bool {
        // ... determine if instance is valid ...
        true
    }
}

// You can create a factory function, or use a closure to create new validator instances.
fn custom_validator_factory<'a>(
    parent: &'a Map<String, Value>,
    value: &'a Value,
    path: Location,
) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
    Ok(Box::new(MyCustomValidator))
}

let validator = jsonschema::options()
    .with_keyword("my-type", custom_validator_factory)
    .with_keyword("my-type-with-closure", |_, _, _| Ok(Box::new(MyCustomValidator)))
    .build(&json!({ "my-type": "my-schema"}))
    .expect("A valid schema");

assert!(validator.is_valid(&json!({ "a": "b"})));
Source§

impl ValidationOptions<Arc<dyn Retrieve>>

Source

pub fn build( &self, schema: &Value, ) -> Result<Validator, ValidationError<'static>>

Build a JSON Schema validator using the current options.

§Example
use serde_json::json;

let schema = json!({"type": "string"});
let validator = jsonschema::options()
    .build(&schema)
    .expect("A valid schema");

assert!(validator.is_valid(&json!("Hello")));
assert!(!validator.is_valid(&json!(42)));
Source

pub fn with_retriever(self, retriever: impl Retrieve + 'static) -> Self

Set a retriever to fetch external resources.

Trait Implementations§

Source§

impl<R: Clone> Clone for ValidationOptions<R>

Source§

fn clone(&self) -> ValidationOptions<R>

Returns a copy of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ValidationOptions

Source§

fn fmt(&self, fmt: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ValidationOptions<Arc<dyn Retrieve>>

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl<R = Arc<dyn Retrieve>> !Freeze for ValidationOptions<R>

§

impl<R = Arc<dyn Retrieve>> !RefUnwindSafe for ValidationOptions<R>

§

impl<R> Send for ValidationOptions<R>
where R: Send,

§

impl<R> Sync for ValidationOptions<R>
where R: Sync,

§

impl<R> Unpin for ValidationOptions<R>
where R: Unpin,

§

impl<R = Arc<dyn Retrieve>> !UnwindSafe for ValidationOptions<R>

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

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

Source§

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
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

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

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

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

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

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

Source§

type Error = Infallible

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

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

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T