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};

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

#[schema_validation]
fn schema_validation(foo: &Foo) -> Result<(), ValidationErrors> {
    if foo.a == "no" {
        field_err("a", "Can't be no", "Try again", errors);
    }
    if foo.b == 0 && foo.a == "no" {
        schema_err("super no", "Done goofd", errors);
    }
}

schema_validation Desugars to:

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