pub struct ValidationOptions<R = Arc<dyn Retrieve>> { /* private fields */ }Expand description
Configuration options for JSON Schema validation.
Implementations§
Source§impl<R> ValidationOptions<R>
impl<R> ValidationOptions<R>
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);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_resource(self, uri: impl Into<String>, resource: Resource) -> Self
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)));Sourcepub fn with_resources(
self,
pairs: impl Iterator<Item = (impl Into<String>, Resource)>,
) -> Self
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)));Sourcepub fn with_registry(self, registry: Registry) -> Self
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 })));Sourcepub fn with_format<N, F>(self, name: N, format: F) -> Self
pub fn with_format<N, F>(self, name: N, format: F) -> 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.
Sourcepub fn with_keyword<N, F>(self, name: N, factory: F) -> Self
pub fn with_keyword<N, F>(self, name: N, factory: F) -> Self
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>>
impl ValidationOptions<Arc<dyn Retrieve>>
Sourcepub fn build(
&self,
schema: &Value,
) -> Result<Validator, ValidationError<'static>>
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)));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.
Trait Implementations§
Source§impl<R: Clone> Clone for ValidationOptions<R>
impl<R: Clone> Clone for ValidationOptions<R>
Source§fn clone(&self) -> ValidationOptions<R>
fn clone(&self) -> ValidationOptions<R>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more