Skip to content

Conditionally apply rule #78

@aumetra

Description

@aumetra

Let's say you have the following context:

struct ValidatorContext {
    allow_non_ascii: bool
}

In this case you want to apply the ascii rule conditionally on a field.

Right now you'd have to write a function like this:

fn conditional_ascii_check(value: &str, ctx: &ValidatorContext) -> garde::Result {
    if ctx.allow_non_ascii {
        return Ok(());
    }

    garde::rules::ascii::apply(&value, ())
}

It would be interesting to have something like a #[garde(if)] statement.

Example:

struct ValidatorContext {
    allow_non_ascii: bool
}

#[derive(Validate)]
#[garde(context(ValidatorContext as ctx))]
pub struct Data {
    #[garde(if(!ctx.allow_non_ascii, ascii))]
    text: String,
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions