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>
impl<'i, R, F: Json> ValidationOptions<'i, R, F>
Sourcepub fn with_draft(self, draft: Draft) -> Self
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.
Sourcepub fn with_content_media_type(
self,
media_type: &'static str,
media_type_check: fn(&str) -> bool,
) -> Self
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);Sourcepub fn without_content_media_type_support(
self,
media_type: &'static str,
) -> Self
pub fn without_content_media_type_support( self, media_type: &'static str, ) -> Self
Remove support for a specific content media type validation.
Sourcepub fn with_content_encoding(
self,
encoding: &'static str,
check: fn(&str) -> bool,
converter: fn(&str) -> Result<Option<String>, ValidationError<'static>>,
) -> Self
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 (returntrueif valid)converter: Converts the input string, returning:Err(ValidationError): For supported errorsOk(None): If input is invalidOk(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);Sourcepub fn without_content_encoding_support(
self,
content_encoding: &'static str,
) -> Self
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");Sourcepub fn with_base_uri(self, base_uri: impl Into<String>) -> Self
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/".pub fn with_registry(self, registry: &'i Registry<'i>) -> Self
Sourcepub fn with_format<N, Check>(self, name: N, format: Check) -> Self
pub fn with_format<N, Check>(self, name: N, format: Check) -> Self
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!")));Sourcepub fn should_validate_formats(self, yes: bool) -> Self
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.
Sourcepub fn should_ignore_unknown_formats(self, yes: bool) -> Self
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.
Sourcepub fn with_vocabulary(self, uri: impl Into<String>) -> Self
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");Sourcepub fn with_keyword<N, Factory>(self, name: N, factory: Factory) -> Self
pub fn with_keyword<N, Factory>(self, name: N, factory: Factory) -> Self
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>
impl<F: Json> ValidationOptions<'_, Arc<dyn Retrieve>, F>
Sourcepub fn build(
&self,
schema: &Value,
) -> Result<Validator<F>, ValidationError<'static>>
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.
Sourcepub fn build_map(
&self,
schema: &Value,
) -> Result<ValidatorMap<F>, ValidationError<'static>>
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.
Sourcepub fn bundle(&self, schema: &Value) -> Result<Value, Error>
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.
Sourcepub fn dereference(&self, schema: &Value) -> Result<Value, Error>
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.
Sourcepub fn with_retriever(self, retriever: impl Retrieve + 'static) -> Self
pub fn with_retriever(self, retriever: impl Retrieve + 'static) -> Self
Set a retriever to fetch external resources.
Sourcepub fn offline(self) -> Self
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());Sourcepub fn with_http_options(
self,
options: &HttpOptions,
) -> Result<Self, HttpRetrieverError>
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
Sourcepub fn with_pattern_options<E>(self, options: PatternOptions<E>) -> Self
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");Sourcepub fn with_email_options(self, options: EmailOptions) -> Self
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>
impl<'i, F: Json> ValidationOptions<'i, Arc<dyn AsyncRetrieve>, F>
Sourcepub async fn build(
&self,
schema: &Value,
) -> Result<Validator<F>, ValidationError<'static>>
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.
Sourcepub fn offline(self) -> Self
pub fn offline(self) -> Self
Refuse to fetch any reference that is not already in the registry.
Sourcepub async fn build_map(
&self,
schema: &Value,
) -> Result<ValidatorMap<F>, ValidationError<'static>>
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.
Sourcepub async fn bundle(&self, schema: &Value) -> Result<Value, Error>
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.
Sourcepub async fn dereference(&self, schema: &Value) -> Result<Value, Error>
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.