Skip to main content

ValidationOptions

Struct ValidationOptions 

Source
pub struct ValidationOptions<'i, R = Arc<dyn Retrieve>, F: Json = SerdeJson> { /* private fields */ }
Expand description

Configuration options for JSON Schema validation.

F selects the JSON representation the built validator accepts.

Implementations§

Source§

impl<'i, R, F: Json> ValidationOptions<'i, R, F>

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);
§Panics

Panics if Draft::Unknown is provided. Draft::Unknown is internal-only and represents custom meta-schemas that are resolved automatically from the registry.

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_base_uri(self, base_uri: impl Into<String>) -> Self

Establish an anchor for resolving relative schema references during validation.

Relative URIs found within the schema will be interpreted against this base. This is especially useful when validating schemas loaded from sources without an inherent base URL.

§Example

let validator = jsonschema::options()
// Define a base URI for resolving relative references.
    .with_base_uri("https://example.com/schemas/")
    .build(&json!({
        "$id": "relative-schema.json",
        "type": "object"
    }))?;

// Relative URIs in the schema will now resolve against "https://example.com/schemas/".
Source

pub fn with_registry(self, registry: &'i Registry<'i>) -> Self

Source

pub fn with_format<N, Check>(self, name: N, format: Check) -> Self
where N: Into<String>, Check: 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.

A meta-schema that asserts formats rejects unrecognized ones regardless of this setting.

Source

pub fn with_vocabulary(self, uri: impl Into<String>) -> Self

Declare support for a vocabulary this crate does not implement itself.

A meta-schema that requires an unknown vocabulary is rejected. Use this together with ValidationOptions::with_keyword to declare that the vocabulary’s keywords are covered.

let options = jsonschema::options()
    .with_vocabulary("https://example.com/vocab/data");
Source

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

Register a custom keyword validator.

§Example

struct MyCustomValidator;

impl<'i> Keyword<'i> for MyCustomValidator {
    fn validate(&self, instance: &'i Value) -> Result<(), ValidationError<'i>> {
        if !instance.is_object() {
            return Err(ValidationError::custom("expected an object"));
        }
        Ok(())
    }

    fn is_valid(&self, instance: &'i Value) -> bool {
        instance.is_object()
    }
}

fn custom_validator_factory<'a>(
    _parent: &'a Map<String, Value>,
    _value: &'a Value,
    _path: Location,
) -> Result<Box<dyn for<'i> Keyword<'i>>, 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<F: Json> ValidationOptions<'_, Arc<dyn Retrieve>, F>

Source

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

Build a JSON Schema validator using the current options.

If no draft is set via with_draft, the draft is auto-detected from the schema’s $schema field, identical to validator_for.

§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)));
§Errors

Returns an error if schema is invalid for the selected draft or if referenced resources cannot be retrieved or resolved.

§Panics

This method must not be called from within an async runtime if the schema contains external references that require network requests, or it will panic when attempting to block. Use async_options and its async build method for async contexts, or run this in a separate blocking thread via tokio::task::spawn_blocking.

Source

pub fn build_map( &self, schema: &Value, ) -> Result<ValidatorMap<F>, ValidationError<'static>>

Build a ValidatorMap — a map of compiled validators keyed by URI-fragment JSON pointer — from a schema document.

Every reachable subschema is compiled eagerly. The root schema is always present under the key "#".

§Errors

Returns an error if schema is invalid for the selected draft or if referenced resources cannot be retrieved or resolved.

§Panics

This method must not be called from within an async runtime if the schema contains external references that require network requests, or it will panic when attempting to block. Use async_options and its async build_map method for async contexts, or run this in a separate blocking thread via tokio::task::spawn_blocking.

Source

pub fn bundle(&self, schema: &Value) -> Result<Value, Error>

Bundle a JSON Schema into a Compound Schema Document.

All externally-referenced schemas reachable via $ref are embedded in a draft-appropriate container (definitions for Draft 4/6/7, $defs for Draft 2019-09/2020-12). Original $ref values are preserved, and the bundled document validates identically.

For mixed-draft bundles, embedded resources may include both id and $id to maximize interoperability with downstream validators that differ in draft handling.

§Errors

Returns an error if draft detection fails, registry construction fails, subresource scope resolution fails, or any $ref cannot be resolved.

§Panics

This method must not be called from within an async runtime if the schema contains external references that require network requests, or it will panic when attempting to block. Use async_options and its async bundle method for async contexts, or run this in a separate blocking thread via tokio::task::spawn_blocking.

Source

pub fn dereference(&self, schema: &Value) -> Result<Value, Error>

Dereference a JSON Schema by recursively replacing all $ref values with the schemas they point to.

Circular references are left in place as $ref strings.

§Errors

Returns an error if draft detection fails, registry construction fails, subresource scope resolution fails, or any $ref cannot be resolved.

§Panics

This method must not be called from within an async runtime if the schema contains external references that require network requests, or it will panic when attempting to block. Use async_options and its async dereference method for async contexts, or run this in a separate blocking thread via tokio::task::spawn_blocking.

Source

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

Set a retriever to fetch external resources.

Source

pub fn offline(self) -> Self

Refuse to fetch any reference that is not already in the registry.

§Examples
use serde_json::json;

let schema = json!({"$ref": "https://example.com/schema.json"});
assert!(jsonschema::options().offline().build(&schema).is_err());
Source

pub fn with_http_options( self, options: &HttpOptions, ) -> Result<Self, HttpRetrieverError>

Configure HTTP client options for the built-in HTTP retriever.

This creates an HttpRetriever with the provided options and configures it as the retriever for external schemas.

Note: If both connect_timeout and timeout are set, the timeout acts as an upper bound on the total request time, including connection. If timeout < connect_timeout, the connection may be aborted before the connect timeout is reached.

§Example
use std::time::Duration;
use serde_json::json;
use jsonschema::HttpOptions;

let schema = json!({"$ref": "https://example.com/schema.json"});
let http_options = HttpOptions::new()
    .connect_timeout(Duration::from_secs(10))
    .timeout(Duration::from_secs(30));
let validator = jsonschema::options()
    .with_http_options(&http_options)
    .expect("Failed to create HTTP retriever")
    .build(&schema);
§Errors

Returns an error if:

  • The certificate file cannot be read
  • The certificate is not valid PEM
  • The HTTP client cannot be built
Source

pub fn with_pattern_options<E>(self, options: PatternOptions<E>) -> Self

Configure the regular expression engine used during validation for keywords like pattern or patternProperties.

The default engine is fancy-regex, which supports advanced features (e.g., backreferences, look-around). Be aware that using these may lead to exponential runtime due to backtracking. For simpler regexes without these features, regex provides linear time performance.

§Example
use serde_json::json;
use jsonschema::PatternOptions;

let schema = json!({"type": "string"});

// Set backtracking limit to 20000.
let validator = jsonschema::options()
    .with_pattern_options(
        PatternOptions::fancy_regex()
            .backtrack_limit(20000)
    )
    .build(&schema)
    .expect("A valid schema");
Source

pub fn with_email_options(self, options: EmailOptions) -> Self

Set email validation options to customize email format validation behavior.

§Example
use jsonschema::EmailOptions;

let schema = serde_json::json!({"format": "email", "type": "string"});
let validator = jsonschema::options()
    .with_email_options(EmailOptions::default())
    .should_validate_formats(true)
    .build(&schema)
    .expect("A valid schema");
Source§

impl<'i, F: Json> ValidationOptions<'i, Arc<dyn AsyncRetrieve>, F>

Source

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

Build a JSON Schema validator using the current async options.

§Errors

Returns an error if schema is invalid for the selected draft or if referenced resources cannot be retrieved or resolved.

Source

pub fn offline(self) -> Self

Refuse to fetch any reference that is not already in the registry.

Source

pub async fn build_map( &self, schema: &Value, ) -> Result<ValidatorMap<F>, ValidationError<'static>>

Build a ValidatorMap using async retrieval for external references.

Async counterpart to ValidationOptions::build_map.

§Errors

Returns an error if schema is invalid for the selected draft or if referenced resources cannot be retrieved or resolved.

Source

pub async fn bundle(&self, schema: &Value) -> Result<Value, Error>

Bundle a JSON Schema using async retrieval for external references.

Async counterpart to ValidationOptions::bundle.

§Errors

Returns an error if any $ref cannot be resolved, or if the schema draft is older than 2019-09.

Source

pub async fn dereference(&self, schema: &Value) -> Result<Value, Error>

Dereference a JSON Schema using async retrieval for external references.

Async counterpart to ValidationOptions::dereference.

§Errors

Returns an error if any $ref cannot be resolved.

Source

pub fn with_retriever( self, retriever: impl AsyncRetrieve + 'static, ) -> ValidationOptions<'i, Arc<dyn AsyncRetrieve>, F>

Trait Implementations§

Source§

impl<R: Clone, F: Json> Clone for ValidationOptions<'_, R, F>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<R, F: Json> Debug for ValidationOptions<'_, R, F>

Source§

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

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

impl<F: Json> Default for ValidationOptions<'_, Arc<dyn Retrieve>, F>

Source§

fn default() -> Self

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

impl<F: Json> Default for ValidationOptions<'_, Arc<dyn AsyncRetrieve>, F>

Available on crate feature resolve-async only.
Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl<'i, R = Arc<dyn Retrieve>, F = SerdeJson> !RefUnwindSafe for ValidationOptions<'i, R, F>

§

impl<'i, R = Arc<dyn Retrieve>, F = SerdeJson> !UnwindSafe for ValidationOptions<'i, R, F>

§

impl<'i, R, F> Freeze for ValidationOptions<'i, R, F>
where R: Freeze, AHashMap<String, Arc<dyn KeywordFactory<F>>>: Freeze, PhantomData<F>: Freeze,

§

impl<'i, R, F> Send for ValidationOptions<'i, R, F>
where R: Send, AHashMap<String, Arc<dyn KeywordFactory<F>>>: Send, PhantomData<F>: Send,

§

impl<'i, R, F> Sync for ValidationOptions<'i, R, F>
where R: Sync, AHashMap<String, Arc<dyn KeywordFactory<F>>>: Sync, PhantomData<F>: Sync,

§

impl<'i, R, F> Unpin for ValidationOptions<'i, R, F>
where R: Unpin, AHashMap<String, Arc<dyn KeywordFactory<F>>>: Unpin, PhantomData<F>: Unpin,

§

impl<'i, R, F> UnsafeUnpin for ValidationOptions<'i, R, F>
where R: UnsafeUnpin, AHashMap<String, Arc<dyn KeywordFactory<F>>>: UnsafeUnpin, PhantomData<F>: UnsafeUnpin,

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Inspect for T
where T: Debug,

Source§

fn inspect(&self) -> String

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = !

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

fn try_from(value: U) -> Result<T, !>

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> Ungil for T
where T: Send,

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