Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conditionally apply rule #78

Open
aumetra opened this issue Nov 11, 2023 · 0 comments
Open

Conditionally apply rule #78

aumetra opened this issue Nov 11, 2023 · 0 comments

Comments

@aumetra
Copy link
Contributor

aumetra commented Nov 11, 2023

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,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant