Skip to main content

Validate

Derive Macro Validate 

Source
#[derive(Validate)]
{
    // Attributes available to this derive:
    #[vld]
}
Expand description

Derive macro that generates vld_parse(), parse_value(), validate_fields(), and parse_lenient() methods for a struct, plus implements the VldParse trait.

§Usage

use vld::Validate;

#[derive(Debug, Validate)]
struct User {
    #[vld(vld::string().min(2).max(50))]
    name: String,
    #[vld(vld::string().email())]
    email: String,
    #[vld(vld::number().int().gte(18).optional())]
    age: Option<i64>,
}

let user = User::vld_parse(r#"{"name": "Alex", "email": "a@b.com"}"#).unwrap();

§Serde rename support

The derive macro respects #[serde(rename = "...")] on fields and #[serde(rename_all = "...")] on the struct:

#[derive(Debug, serde::Serialize, Validate)]
#[serde(rename_all = "camelCase")]
struct ApiRequest {
    #[vld(vld::string().min(2))]
    first_name: String,
    #[vld(vld::string().email())]
    email_address: String,
}
// Parses from {"firstName": "...", "emailAddress": "..."}

Supported rename_all conventions: camelCase, PascalCase, snake_case, SCREAMING_SNAKE_CASE, kebab-case, SCREAMING-KEBAB-CASE.

The expression inside #[vld(...)] is used as-is in the generated code. Make sure the types are in scope (e.g., use vld::string() or import via prelude).