Skip to main content

Validate

Derive Macro Validate 

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

Derive macro for field validation.

Generates a validate() method that checks field constraints at runtime.

§Attributes

  • #[validate(min = N)] - Minimum value for numbers
  • #[validate(max = N)] - Maximum value for numbers
  • #[validate(min_length = N)] - Minimum length for strings
  • #[validate(max_length = N)] - Maximum length for strings
  • #[validate(pattern = "regex")] - Regex pattern for strings
  • #[validate(email)] - Email format validation
  • #[validate(url)] - URL format validation
  • #[validate(required)] - Mark an Option field as required
  • #[validate(custom = "fn_name")] - Custom validation function

§Example

use sqlmodel::Validate;

#[derive(Validate)]
struct User {
    #[validate(min_length = 1, max_length = 100)]
    name: String,

    #[validate(min = 0, max = 150)]
    age: i32,

    #[validate(email)]
    email: String,

    #[validate(required)]
    team_id: Option<i64>,
}

let user = User {
    name: "".to_string(),
    age: 200,
    email: "invalid".to_string(),
    team_id: None,
};

// Returns Err with all validation failures
let result = user.validate();
assert!(result.is_err());