Skip to content

use garde::Validate::validate as nutype validator #253

Description

@raffomania

I use garde for generating detailed and nested error reports for users when validation fails.
At the same time, I'd like to use nutype to ensure only validated values are used throughout my code.
So I'd like to derive garde::Validate on my nutype struct and then use it as a validator when constructing it:

#[nutype(
    validate(with = garde::Validate::validate, error = garde::Report),
    derive_unchecked(garde::Validate)
)]
pub struct Username(#[garde(length(min = 1))] String);

This is different from #228 which supports calling validate after the newtype has been constructed.

This snippet currently results in an error with nutype 0.8.0-beta.1:

error[E0277]: the trait bound `std::string::String: garde::Validate` is not satisfied
  --> src/buildspace.rs:10:1
   |
10 | / #[nutype(
11 | |     validate(with = garde::Validate::validate, error = garde::Report),
   | |                     ------------------------- required by a bound introduced by this call
12 | |     derive_unchecked(garde::Validate)
13 | | )]
   | |__^ the trait `garde::Validate` is not implemented for `std::string::String`

and I think that makes sense, because validate is designed to run on the outer struct, but nutype's validators run on the inner value.

A workaround might be to introduce a second newtype for the inner value, derive Validate on that, and call its validate method using nutype. This has two drawbacks. First, it's inconvenient. Second, it doesn't allow garde to validate nutype structs nested in another struct, e.g. if we were to extend the Username example from above:

#[derive(Validate)]
pub struct CreateUser {
    #[garde(dive)]
    pub username: Username,
}

I'm not sure if nested validation can be made to work, since nutype runs while the struct is created, and garde after. 🤔

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