Thanks to visit codestin.com
Credit goes to docs.rs

Struct jsonschema::ValidationOptions

source ·
pub struct ValidationOptions { /* private fields */ }
Expand description

Configuration options for JSON Schema validation.

Implementations§

source§

impl ValidationOptions

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 compile<'a>( &self, schema: &'a Value, ) -> Result<Validator, ValidationError<'a>>

👎Deprecated since 0.20.0: Use ValidationOptions::build instead

Build a JSON Schema validator using the current options.

DEPRECATED: Use ValidationOptions::build instead.

source

pub fn with_draft(&mut self, draft: Draft) -> &mut 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( &mut self, media_type: &'static str, media_type_check: fn(_: &str) -> bool, ) -> &mut 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 with_resolver( &mut self, resolver: impl SchemaResolver + 'static, ) -> &mut Self

Set a custom resolver for external references.

source

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

Remove support for a specific content media type validation.

source

pub fn with_content_encoding( &mut self, encoding: &'static str, check: fn(_: &str) -> bool, converter: fn(_: &str) -> Result<Option<String>, ValidationError<'static>>, ) -> &mut 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( &mut self, content_encoding: &'static str, ) -> &mut Self

Remove support for a specific content encoding.

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

pub fn with_meta_schemas(&mut self) -> &mut Self

👎Deprecated since 0.19.0: Meta schemas are now included by default

Add meta schemas for supported JSON Schema drafts. It is helpful if your schema has references to JSON Schema meta-schemas:

{
    "schema": {
        "multipleOf": {
            "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf"
        },
        "maximum": {
            "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum"
        }
    }
}

The example above is taken from the Swagger 2.0 JSON schema.

source

pub fn with_document(&mut self, id: String, document: Value) -> &mut Self

Add a document to the store.

Acts as a cache to avoid network calls for remote schemas referenced by $ref.

source

pub fn with_format<N, F>(&mut self, name: N, format: F) -> &mut 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(&mut self, yes: bool) -> &mut 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(&mut self, yes: bool) -> &mut 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>(&mut self, name: N, factory: F) -> &mut Self
where N: Into<String>, F: for<'a> Fn(&'a Map<String, Value>, &'a Value, JsonPointer) -> Result<Box<dyn Keyword>, ValidationError<'a>> + Send + Sync + 'static,

Register a custom keyword validator.

§Example

struct MyCustomValidator;

impl Keyword for MyCustomValidator {
    fn validate<'instance>(
        &self,
        instance: &'instance Value,
        instance_path: &JsonPointerNode,
    ) -> ErrorIterator<'instance> {
        // ... validate instance ...
        if !instance.is_object() {
            let error = ValidationError::custom(
                JsonPointer::default(),
                instance_path.into(),
                instance,
                "Boom!",
            );
            Box::new(once(error))
        } else {
            Box::new(None.into_iter())
        }
    }
    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: JsonPointer,
) -> 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"})));

Trait Implementations§

source§

impl Clone for ValidationOptions

source§

fn clone(&self) -> ValidationOptions

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

source§

fn default() -> Self

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

Auto Trait Implementations§

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, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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