Attribute Macro validify::schema_validation

source ·
#[schema_validation]
Expand description

A shortcut for ergonomic error creation in custom schema validator functions.

Prepends a let mut errors = ValidationErrors::new() to the beginning of the function block, and appends a if errors.is_empty() { Ok(()) } else { Err(errors) } to the end.

Designed to be used in conjuction with the field_err and schema_err macros.

use validify::{ValidationErrors, Validify, schema_validation, schema_err};

#[derive(Debug, Clone, Validify)]
#[validate(validate_schema)]
struct Foo {
    a: String,
    b: usize,
}

#[schema_validation]
fn validate_schema(foo: &Foo) -> Result<(), ValidationErrors> {
    if foo.b == 0 && foo.a == "no" {
        schema_err("super no", "Done goofd");
    }
}

validate_schema Desugars to:

fn validate_schema(foo: &Foo) -> Result<(), ValidationErrors> {
    let mut errors = validify::ValidationErrors::new();
    if foo.b == 0 && foo.a == "no" {
        errors.add(validify::ValidationError::new_schema("super no").with_message("Done goofd".to_string()));
    }
    if errors.is_empty() { Ok(()) } else { Err(errors) }
}