Function rocket::form::validate::with

source ·
pub fn with<'v, V, F, M>(value: V, f: F, msg: M) -> Result<'v, ()>
where F: FnOnce(V) -> bool, M: Into<Cow<'static, str>>,
Expand description

With validator: succeeds when an arbitrary function or closure does.

This is the most generic validator and, for readability, should only be used when a more case-specific option does not exist. It succeeds exactly when f returns true and fails otherwise.

On error, returns a validation error with the message msg.


use rocket::form::{FromForm, FromFormField};

#[derive(PartialEq, FromFormField)]
enum Pet { Cat, Dog }

fn is_dog(p: &Pet) -> bool {
    matches!(p, Pet::Dog)

struct Foo {
    // These are equivalent. Prefer the former.
    #[field(validate = contains(Pet::Dog))]
    #[field(validate = with(|pets| pets.iter().any(|p| *p == Pet::Dog), "missing dog"))]
    pets: Vec<Pet>,
    // These are equivalent. Prefer the former.
    #[field(validate = eq(Pet::Dog))]
    #[field(validate = with(|p| matches!(p, Pet::Dog), "expected a dog"))]
    #[field(validate = with(|p| is_dog(p), "expected a dog"))]
    #[field(validate = with(is_dog, "expected a dog"))]
    dog: Pet,
    // These are equivalent. Prefer the former.
    #[field(validate = contains(&]
    #[field(validate = with(|pets| pets.iter().any(|p| p == &, "missing dog"))]
    one_dog_please: Vec<Pet>,