Search code examples
rust

Unexpected type `string` for rust validator crate with regex?


I'm a begginner at rust and still mostly confused. In my current module I'm trying to use the validtor create as the docs suggest.

use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use sqlx::types::Uuid;
use validator::Validate;

static RE_PASSWORDS: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$").unwrap());

#[derive(Debug, Deserialize, Validate)]
pub struct CreateUserDto {
    #[validate(length(min = 1, max = 100))]
    pub name: String,
    #[validate(email)]
    pub email: String,
    #[validate(regex = "RE_PASSWORDS")] // <- Unexpected type `string`
    pub password: String,
}

I'm seeing the following error error that I marked in the snipped, though: Unexpected type 'string'.

I tried the alternative syntax (I'm not sure what the difference between the two is, although the error suggest that it has to do with dereferencing):

#[validate(regex(path = "RE_PASSWORDS"))]

This produces a new error, though:

the trait bound once_cell::sync::Lazy<regex::Regex>: validator::validation::regex::AsRegex is not satisfied required for &once_cell::sync::Lazy<regex::Regex> to implement validator::validation::regex::AsRegex

[dependencies]
[...]
once_cell = "1.19.0"
dotenv = "0.15.0"
regex = "1.10.6"
validator_derive = "0.18.1"
lazy_static = "1.5.0"

Can someone help?


Solution

  • The readme on crates.io is out of date. There is an issue in the repo here with a fix in

    #[derive(Debug, Deserialize, Validate)]
    pub struct CreateUserDto {
        #[validate(regex(path = "*RE_PASSWORDS"))] // Note '*' in path
        pub password: String,
    }
    

    It looks like the alternative form suggested in the updated readme (validate(regex = *RE_PASSWORDS)) still doesn't work.