Function jtd::validate[][src]

pub fn validate<'a>(
    schema: &'a Schema,
    instance: &'a Value,
    options: ValidateOptions
) -> Result<Vec<ValidationErrorIndicator<'a>>, ValidateError>

Validates a schema against an instance, returning a set of error indicators.

In keeping with the conventions of RFC8927, the "input" JSON -- the second argument to this function -- is called an instance.

The set of error indicators returned is specified by the JSON Typedef specification. The ordering of those errors is not defined by the JSON Typedef specification, and is subject to change in a future version of this crate.

use jtd::{Schema, ValidationErrorIndicator, ValidateOptions};
use serde_json::json;

let schema = Schema::from_serde_schema(
    serde_json::from_value(json!({
        "elements": {
            "type": "uint8"
        }
    })).unwrap()).unwrap();

let instance = serde_json::json!([ "a", "b", "c" ]);

// By default, jtd::validate() will return all errors in the input.
let validate_options = ValidateOptions::new();
let errors = jtd::validate(&schema, &instance, validate_options).unwrap();
assert_eq!(
    vec![
        ValidationErrorIndicator {
            instance_path: vec!["0".to_owned().into()],
            schema_path: vec!["elements".into(), "type".into()],
        },
        ValidationErrorIndicator {
            instance_path: vec!["1".to_owned().into()],
            schema_path: vec!["elements".into(), "type".into()],
        },
        ValidationErrorIndicator {
            instance_path: vec!["2".to_owned().into()],
            schema_path: vec!["elements".into(), "type".into()],
        },
    ],
    errors,
);

// If you don't care about validation errors beyond a certain amount of
// errors, use with_max_errors on the ValidateOptions you pass to validate.
let validate_options = ValidateOptions::new().with_max_errors(1);
let errors = jtd::validate(&schema, &instance, validate_options).unwrap();
assert_eq!(
    vec![
        ValidationErrorIndicator {
            instance_path: vec!["0".to_owned().into()],
            schema_path: vec!["elements".into(), "type".into()],
        },
    ],
    errors,
);

Security considerations

(This note is copied from the top-level documentation, because it's important.)

If you're running validate() with untrusted schemas (untrusted inputs is fine), then be aware of this security consideration from RFC 8927:

Implementations that evaluate user-inputted schemas SHOULD implement mechanisms to detect and abort circular references that might cause a naive implementation to go into an infinite loop. Without such mechanisms, implementations may be vulnerable to denial-of-service attacks.

This crate supports that "detect and abort" mechanism via ValidateOptions::with_max_depth. Please see that documentation if you're validating data against untrusted schemas.