### Email Rule Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Demonstrates the email validation rule. Checks for a valid email format. ```rust use garde::Validate; #[derive(Validate)] struct Contact { #[garde(email)] address: String, } assert!(Contact { address: "user@example.com".to_string() }.validate().is_ok()); assert!(Contact { address: "invalid@.com".to_string() }.validate().is_err()); ``` -------------------------------- ### Add Garde to Project Source: https://github.com/jprochazk/garde/blob/main/README.md Install the Garde crate with the 'full' feature flag using Cargo. ```text cargo add garde -F full ``` -------------------------------- ### Suffix Rule Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Demonstrates how to use the suffix validation rule. Ensures the string ends with '.png'. ```rust use garde::Validate; #[derive(Validate)] struct Filename { #[garde(suffix(".png"))] image: String, } assert!(Filename { image: "logo.png".to_string() }.validate().is_ok()); assert!(Filename { image: "logo.jpg".to_string() }.validate().is_err()); ``` -------------------------------- ### Example Struct with Skip Source: https://github.com/jprochazk/garde/blob/main/garde/README.md Demonstrates the usage of `#[garde(length(min = 1))]` and `#[garde(skip)]` on struct fields. ```rust #[derive(garde::Validate)] struct Foo<'a> { #[garde(length(min = 1))] a: &'a str, #[garde(skip)] b: &'a str, // this field will not be validated } ``` -------------------------------- ### Basic Validation Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/README.md Demonstrates basic field validation using derive macros for length and email rules. Shows how to handle validation errors. ```rust use garde::Validate; #[derive(Validate)] struct User { #[garde(length(min = 3, max = 20))] username: String, #[garde(email)] email: String, } let user = User { username: "ab".to_string(), email: "invalid-email".to_string(), }; match user.validate() { Ok(()) => println!("User is valid"), Err(report) => { for (path, error) in report.iter() { println!("{}: {}", path, error); } // Output: // username: length is lower than 3 // email: not a valid email: value is missing `@` } } ``` -------------------------------- ### Skip Validation Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Demonstrates skipping validation for multiple fields, including internal state and system fields. ```rust use garde::Validate; #[derive(Validate)] struct Entity { #[garde(length(min = 1))] name: String, #[garde(skip)] internal_state: String, // Not validated #[garde(skip)] timestamp: u64, // System field } ``` -------------------------------- ### Install Garde with Derive Feature Source: https://github.com/jprochazk/garde/blob/main/_autodocs/README.md Add the Garde crate to your Cargo.toml with the 'derive' feature enabled to use its derive macros. ```toml [dependencies] garde = { version = "0.23", features = ["derive"] } ``` -------------------------------- ### Pattern Rule Example (LazyLock Regex) Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Demonstrates using the pattern rule with a pre-compiled Regex using LazyLock. This is useful for complex or frequently used patterns. ```rust use garde::Validate; use std::sync::LazyLock; use regex::Regex; static EMAIL_PATTERN: LazyLock = LazyLock::new(|| Regex::new(r"^[^@]+@[^@]+\.[a-z]{2,}$").unwrap()); #[derive(Validate)] struct Account { #[garde(pattern(EMAIL_PATTERN))] email: String, } ``` -------------------------------- ### Validate Method Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validate-trait.md Demonstrates validating a struct with a length constraint using the default context. Use this when no custom context is needed. ```rust use garde::Validate; #[derive(Validate)] struct User { #[garde(length(min = 3, max = 20))] username: String, } let user = User { username: "ab".to_string(), }; match user.validate() { Ok(()) => println!("User is valid"), Err(report) => println!("Validation failed: {}", report), } ``` -------------------------------- ### Example: Basic Field Validation with Skip Source: https://github.com/jprochazk/garde/blob/main/README.md Demonstrates basic length validation on field 'a' and skipping validation for field 'b' using `#[garde(skip)]`. ```rust struct Foo<'a> { #[garde(length(min = 1))] a: &'a str, #[garde(skip)] b: &'a str, // this field will not be validated } ``` -------------------------------- ### Derive Macro Implementation Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Shows how the `#[derive(Validate)]` macro generates a `Validate` implementation for a struct with a length-constrained field. ```rust use garde::Validate; // Input #[derive(Validate)] struct User { #[garde(length(min = 3))] name: String, } // Generates (simplified) impl garde::Validate for User { type Context = (); fn validate_into( &self, ctx: &Self::Context, parent: &mut dyn FnMut() -> garde::Path, report: &mut garde::Report, ) { // Validation logic for 'name' field let mut path = garde::util::nested_path!(parent, "name"); garde::rules::length::apply(&self.name, (3, usize::MAX))? .map_err(|e| { report.append(path(), e); }) .ok(); } } ``` -------------------------------- ### IP Address Validation Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Demonstrates validating IPv4, IPv6, and any IP address formats within a single struct. Ensures correct usage of ip, ipv4, and ipv6 rules. ```rust use garde::Validate; #[derive(Validate)] struct Network { #[garde(ipv4)] ipv4: String, #[garde(ipv6)] ipv6: String, #[garde(ip)] any_ip: String, } assert!(Network { ipv4: "192.168.1.1".to_string(), ipv6: "::1".to_string(), any_ip: "10.0.0.1".to_string(), }.validate().is_ok()); ``` -------------------------------- ### Pattern Rule Example (String Literal) Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Demonstrates using the pattern rule with a string literal regex. Ensures the string consists only of uppercase letters. ```rust use garde::Validate; #[derive(Validate)] struct Input { #[garde(pattern(r"^[A-Z]+$"))] code: String, } assert!(Input { code: "ABC".to_string() }.validate().is_ok()); assert!(Input { code: "abc".to_string() }.validate().is_err()); ``` -------------------------------- ### Prefix Rule Validation Source: https://github.com/jprochazk/garde/blob/main/_autodocs/errors.md Demonstrates the 'prefix' rule for string-like types. Use this to ensure a string starts with a specific pattern. ```rust use garde::Validate; #[derive(Validate)] struct Token { #[garde(prefix("auth_"))] value: String, } let token = Token { value: "invalid_token".to_string() }; // Error: "value: value does not begin with \"auth_\"" ``` -------------------------------- ### Nested Path Example with `select!` Macro Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Shows how to use the `select!` macro with nested paths, specifically for validating elements within a `Vec`. It also demonstrates an alternative approach using `report.iter()` for dynamic path iteration when `select!`'s static paths are insufficient. ```rust #[derive(Validate)] struct Team { #[garde(inner(length(min = 1)))] members: Vec, } if let Err(report) = team.validate() { // Select errors from first member let first_member_errors = select!(report, members[0]); // Select all member errors for i in 0..team.members.len() { let path_str = format!("members[{}]", i); // Note: select! doesn't support dynamic paths, use iter() instead } // Alternative: use iter() for dynamic paths for (path, error) in report.iter() { println!("{}: {}", path, error); } } ``` -------------------------------- ### Garde Field Attributes Examples Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Provides examples of various field attributes available in Garde for defining validation rules, including single/multiple rules, skipping validation, nested validation, and using rule adapters. ```rust #[garde(rule1]] // Single rule #[garde(rule1, rule2)] // Multiple rules #[garde(rule1, rule2, rule3)] // Many rules #[garde(skip)] // Skip validation #[garde(allow_unvalidated)] // Invert validation (field-level) #[garde(dive)] // Nested validation #[garde(dive(context_field))] #[garde(inner(rule1))] #[garde(inner(rule1, rule2))] #[garde(inner(inner(rule1)))] #[garde(adapt(module))] #[garde(transparent)] // Newtype transparency (struct-level) ``` -------------------------------- ### `select!` Macro Syntax Examples Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Illustrates the syntax for using the `select!` macro to navigate nested structures and arrays within a validation report. It covers field names, array indices, and mixed path combinations. ```rust select!(report, path.to.field) select!(report, field[index]) select!(report, complex[0].nested.path[1].field) ``` -------------------------------- ### Newtype Transparent Validation Example Source: https://github.com/jprochazk/garde/blob/main/README.md Illustrates the flattened error message produced by a transparent newtype compared to a non-transparent one. ```rust,ignore User { username: Username("") }.validate() "username: length is lower than 3" ``` ```rust,ignore User { username: Username("") }.validate() "username[0]: length is lower than 3" ``` -------------------------------- ### Derive Macro Usage Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/configuration.md Demonstrates the basic usage of the `#[derive(Validate)]` macro for struct validation. It requires the 'derive' feature to be enabled. ```rust use garde::Validate; #[derive(Validate)] struct User { #[garde(length(min = 3))] username: String, } ``` -------------------------------- ### Prefix Validation Source: https://github.com/jprochazk/garde/blob/main/_autodocs/types.md The `Prefix` trait allows validation to check if a string starts with a given pattern. ```APIDOC ## Prefix Validation ### Description Validates if a string starts with a specified pattern. ### Trait `Prefix` ### Method `validate_prefix(&self, pattern: &str) -> bool` ``` -------------------------------- ### Example of Contains Rule Usage Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Demonstrates the usage of the 'contains' validation rule for ensuring specific substrings are present in email and URL fields. ```rust use garde::Validate; #[derive(Validate)] struct Message { #[garde(contains("http://"))] url: String, #[garde(contains("@"))] email: String, } assert!(Message { url: "https://http://example.com".to_string(), email: "user@example.com".to_string(), }.validate().is_ok()); ``` -------------------------------- ### Get Path Length Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Returns the number of components in a path. Use to check the depth of an error location. ```rust use garde::Path; let path = Path::new("users").join(0).join("name"); assert_eq!(path.len(), 3); ``` -------------------------------- ### Get Error Message Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Retrieves the error message as a string slice. ```rust pub fn message(&self) -> &str> ``` ```rust use garde::Error; let error = Error::new("invalid email format"); assert_eq!(error.message(), "invalid email format"); ``` -------------------------------- ### Garde Cargo.toml with Regex Build Dependency Source: https://github.com/jprochazk/garde/blob/main/_autodocs/configuration.md Example of configuring Garde with the `regex` feature for compile-time regex validation. This also shows the necessary `regex` dependency for both regular and build dependencies. ```toml [dependencies] garde = { version = "0.23", features = ["derive", "regex"] } regex = { version = "1", features = ["unicode-perl"] } [build-dependencies] regex = { version = "1", features = ["unicode-perl"] } ``` -------------------------------- ### Example Macro Compilation Error Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Illustrates a common compilation error message from the derive macro, indicating an unknown field referenced in a rule. ```text error: unknown field 'username' referenced in 'matches' --> src/lib.rs:5:30 | 5 | #[garde(matches(invalid_field))] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``` -------------------------------- ### Enable Garde with Derive and Common Features Source: https://github.com/jprochazk/garde/blob/main/_autodocs/configuration.md This snippet shows how to enable the derive macro and common features like email and URL validation in your Cargo.toml. It's a recommended starting point for most projects. ```toml [dependencies] garde = { version = "0.23", features = ["derive", "email", "url"] } ``` -------------------------------- ### Validate With Method Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validate-trait.md Shows how to validate a struct using a custom context, allowing validation rules to depend on external configuration. The context is passed via the `#[garde(context(...))]` attribute. ```rust use garde::Validate; #[derive(Validate)] #[garde(context(Config as ctx))] struct User { #[garde(length(min = ctx.min_length, max = ctx.max_length))] username: String, } struct Config { min_length: usize, max_length: usize, } let user = User { username: "john".to_string(), }; let config = Config { min_length: 3, max_length: 20, }; match user.validate_with(&config) { Ok(()) => println!("Valid under config"), Err(report) => println!("Invalid: {}", report), } ``` -------------------------------- ### Prefix Validation Rule Source: https://github.com/jprochazk/garde/blob/main/README.md Validates that a string field starts with a specific prefix. The prefix must be a string literal. ```rust #[garde(prefix())] ``` -------------------------------- ### Valid into_inner Method Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validate-trait.md Demonstrates consuming a `Valid` instance to retrieve the inner, validated value. This is used after a successful validation. ```rust use garde::{Validate, Unvalidated, Valid}; #[derive(Validate)] struct User { #[garde(length(min = 1))] name: String, } let user = Unvalidated::new(User { name: "Alice".to_string(), }); match user.validate() { Ok(valid) => { let inner: User = valid.into_inner(); println!("Got validated user: {:?}", inner); } Err(report) => println!("Invalid: {}", report), } ``` -------------------------------- ### Example Struct with Allow Unvalidated Source: https://github.com/jprochazk/garde/blob/main/garde/README.md Illustrates the use of `#[garde(allow_unvalidated)]` on a struct, where fields like `b` are not validated without explicit `#[garde(skip)]`. ```rust #[derive(garde::Validate)] #[garde(allow_unvalidated)] struct Bar<'a> { #[garde(length(min = 1))] a: &'a str, b: &'a str, // this field will not be validated // note the lack of `#[garde(skip)]` } ``` -------------------------------- ### Conditional Validation for Admin Users Source: https://github.com/jprochazk/garde/blob/main/README.md Use the `if` rule to apply validation rules only when a specific condition is met. This example validates the `username` format only for admin users. ```rust #[derive(garde::Validate)] struct User { #[garde(skip)] is_admin: bool, // Only validate username format for admin users #[garde(if(cond = self.is_admin, ascii, length(min = 8)))] username: String, } ``` -------------------------------- ### Garde Rule Parameters Examples Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Illustrates the various parameters that can be used with Garde's built-in validation rules, such as length, range, contains, pattern, matches, custom functions, and conditional logic. ```rust // Length #[garde(length(min = 1))] #[garde(length(max = 100))] #[garde(length(min = 1, max = 100))] #[garde(length(equal = 16))] #[garde(length(bytes, min = 1, max = 100))] #[garde(length(graphemes, min = 1))] #[garde(length(chars, min = 1))] #[garde(length(utf16, min = 1))] // Range #[garde(range(min = 0))] #[garde(range(max = 100))] #[garde(range(min = 0, max = 100))] #[garde(range(equal = 42))] // Contains, Prefix, Suffix #[garde(contains("substring"))] #[garde(prefix("start_"))] #[garde(suffix(".ext"))] // Pattern #[garde(pattern(r"^[a-z]+$"))] #[garde(pattern(LAZY_REGEX))] // Matches #[garde(matches(other_field))] // Custom #[garde(custom(function))] #[garde(custom(|val, ctx| /* ... */))] // If #[garde(if(cond = self.flag, rule1, rule2))] #[garde(if(cond = ctx.value > 10, rule))] #[garde(if(rule1, cond = expr, rule2))] ``` -------------------------------- ### Custom Validation with Context Source: https://github.com/jprochazk/garde/blob/main/README.md Implement custom validation logic using the `custom` rule and provide a context type. The example defines a `PasswordContext` and a validation function `is_strong_password`. ```rust use garde::Validate; #[derive(garde::Validate)] #[garde(context(PasswordContext))] struct User { #[garde(custom(is_strong_password))] password: String, } struct PasswordContext { min_length: usize, } fn is_strong_password(value: &str, context: &PasswordContext) -> garde::Result { if value.len() < context.min_length { return Err(garde::Error::new("password is not strong enough")); } Ok(()) } let ctx = PasswordContext { min_length: 8 }; let user = User { password: "correct horse battery staple".to_string() }; assert!(user.validate_with(&ctx).is_ok()); ``` -------------------------------- ### Valid Deref Usage Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validate-trait.md Illustrates accessing fields of a validated struct directly through the `Valid` wrapper using its `Deref` implementation. ```rust use garde::{Validate, Unvalidated}; #[derive(Validate)] struct User { #[garde(length(min = 1))] name: String, } let valid_user = Unvalidated::new(User { name: "Alice".to_string(), }).validate().unwrap(); // Dereference to access inner fields directly println!("Name: {}", valid_user.name); ``` -------------------------------- ### Prefix Validation Rule Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Validates that a string-like value starts with a specified prefix. Use this rule when a string must begin with a particular sequence of characters. ```rust use garde::Validate; #[derive(Validate)] struct ApiKey { #[garde(prefix("key_"))] value: String, } ``` -------------------------------- ### Enum Validation with Garde Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Demonstrates how to use the `Validate` derive macro on enums to validate the active variant and its fields. This example shows validation for email and phone number formats. ```rust use garde::Validate; #[derive(Validate)] enum Credential { #[garde(dive)] Email { #[garde(email)] address: String, }, #[garde(dive)] Phone { #[garde(phone_number)] number: String, }, } let cred = Credential::Email { address: "not-an-email".to_string(), }; // Validates the active variant assert!(cred.validate().is_err()); ``` -------------------------------- ### Request Validation in Web Handlers Source: https://github.com/jprochazk/garde/blob/main/_autodocs/README.md Example of validating a `CreateUserRequest` struct within a web handler. After validation, the `req` object is guaranteed to be valid for further use. ```rust use garde::Validate; #[derive(serde::Deserialize, Validate)] struct CreateUserRequest { #[garde(length(min = 3, max = 20))] username: String, #[garde(email)] email: String, #[garde(length(min = 8))] password: String, } fn handle_create_user(req: CreateUserRequest) -> Result { req.validate() .map_err(|report| format!("Validation failed: {}", report))?; // Safe to use req now let user = User::create(&req.username, &req.email)?; Ok(user) } ``` -------------------------------- ### Filtering Validation Errors with `select!` Macro Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Demonstrates how to use the `select!` macro to filter validation errors from a `Report` by a specific field path. This example shows how to extract errors related to the 'username' and 'email' fields. ```rust use garde::{Validate, select}; #[derive(Validate)] struct User { #[garde(length(min = 3))] username: String, #[garde(email)] email: String, } let user = User { username: "ab".to_string(), email: "invalid".to_string(), }; if let Err(report) = user.validate() { // Get all errors for the username field let username_errors = select!(report, username); for error in username_errors { println!("Username error: {}", error); } // Get all errors for the email field let email_errors = select!(report, email); println!("Email error count: {}", email_errors.count()); } ``` -------------------------------- ### Matches Rule Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Use the `matches` rule to ensure a field's value is identical to another field's value within the same struct. This is commonly used for password confirmation or email confirmation fields. ```rust use garde::Validate; #[derive(Validate)] struct Registration { password: String, #[garde(matches(password))] password_confirm: String, } ``` ```rust use garde::Validate; #[derive(Validate)] struct SignUp { password: String, #[garde(matches(password))] password_confirm: String, email: String, #[garde(matches(email))] email_confirm: String, } assert!(SignUp { password: "secret123".to_string(), password_confirm: "secret123".to_string(), email: "user@example.com".to_string(), email_confirm: "user@example.com".to_string(), }.validate().is_ok()); ``` -------------------------------- ### Handling Option Fields with Required Rule Source: https://github.com/jprochazk/garde/blob/main/README.md Use the `required` rule to ensure an `Option` field is `Some` and validate its inner value. The example shows validation for ASCII characters and minimum length. ```rust #[derive(garde::Validate)] struct Test { #[garde(required, ascii, length(min = 1))] value: Option, } ``` -------------------------------- ### Custom Rule Adapter for `&str` Length Source: https://github.com/jprochazk/garde/blob/main/garde/README.md Define a module to adapt Garde's rules for third-party types without using a newtype. This example shows a custom length validation for `&str`. ```rust mod my_str_adapter { #![allow(unused_imports)] pub use garde::rules::*; pub mod length { pub use garde::rules::length::*; pub mod simple { pub fn apply(v: &str, (min, max): (usize, usize)) -> garde::Result { if !(min..=max).contains(&v.len()) { Err(garde::Error::new("my custom error message")) } else { Ok(()) } } } } } ``` -------------------------------- ### Conditional Validation with Multiple Rules Source: https://github.com/jprochazk/garde/blob/main/README.md Multiple validation rules can be combined within a single `if` condition. This example applies ASCII, conditional, and alphanumeric rules to a password field based on a `strict_mode` flag. ```rust #[derive(garde::Validate)] struct Account { #[garde(skip)] strict_mode: bool, #[garde(if(ascii, cond = self.strict_mode, length(min = 12), alphanumeric))] password: String, } ``` -------------------------------- ### Implement I18n Trait for Czech Localization Source: https://github.com/jprochazk/garde/blob/main/_autodocs/configuration.md Implement the `I18n` trait to provide custom error messages for specific locales. This example shows a Czech localization, defining messages for various validation failures. ```rust use garde::{Validate, i18n::I18n, with_i18n}; use std::borrow::Cow; struct Czech; impl I18n for Czech { fn length_lower_than(&self, min: usize) -> Cow<'static, str> { format!("musí obsahovat alespoň {min} znaků").into() } fn email_invalid(&self, _: garde::i18n::InvalidEmail) -> Cow<'static, str> { "email je neplatný".into() } // Implement remaining methods... fn length_greater_than(&self, max: usize) -> Cow<'static, str> { format!("nesmí překročit {max} znaků").into() } fn range_lower_than(&self, min: &dyn std::fmt::Display) -> Cow<'static, str> { format!("menší než {min}").into() } fn range_greater_than(&self, max: &dyn std::fmt::Display) -> Cow<'static, str> { format!("větší než {max}").into() } fn credit_card_invalid(&self, _: garde::i18n::InvalidCreditCard) -> Cow<'static, str> { "neplatné číslo karty".into() } fn pattern_no_match(&self, _: &dyn std::fmt::Display) -> Cow<'static, str> { "neodpovídá vzoru".into() } fn contains_missing(&self, pattern: &dyn std::fmt::Display) -> Cow<'static, str> { format!("neobsahuje \"{pattern}\"").into() } fn url_invalid(&self, _: garde::i18n::InvalidUrl) -> Cow<'static, str> { "neplatná URL".into() } fn prefix_missing(&self, pattern: &dyn std::fmt::Display) -> Cow<'static, str> { format!("nezačíná na \"{pattern}\"").into() } fn suffix_missing(&self, pattern: &dyn std::fmt::Display) -> Cow<'static, str> { format!("nekončí na \"{pattern}\"").into() } fn phone_number_invalid(&self, _: garde::i18n::InvalidPhoneNumber) -> Cow<'static, str> { "neplatné telefonní číslo".into() } fn ip_invalid(&self, kind: garde::i18n::IpKind) -> Cow<'static, str> { format!("neplatná {kind} adresa").into() } fn matches_field_mismatch(&self, field: &dyn std::fmt::Display) -> Cow<'static, str> { format!("neodpovídá poli {field}").into() } fn ascii_invalid(&self) -> Cow<'static, str> { "není ASCII".into() } fn alphanumeric_invalid(&self) -> Cow<'static, str> { "není alfanumerické".into() } fn required_not_set(&self) -> Cow<'static, str> { "je povinné".into() } } #[derive(Validate)] struct User { #[garde(length(min = 3))] username: String, } let user = User { username: "ab".to_string(), }; let result = with_i18n(Czech, || user.validate()); ``` -------------------------------- ### Customize Error Messages with I18n in Rust Source: https://github.com/jprochazk/garde/blob/main/_autodocs/errors.md Demonstrates how to implement internationalized error messages using Garde's `I18n` trait. This allows for localized error feedback, as shown with a Spanish translation example. Ensure all required `I18n` methods are implemented for full localization. ```rust use garde::{Validate, i18n::{I18n, with_i18n}}; use std::borrow::Cow; struct Spanish; impl I18n for Spanish { fn length_lower_than(&self, min: usize) -> Cow<'static, str> { format!("debe tener al menos {min} caracteres").into() } // Implement other methods... fn length_greater_than(&self, max: usize) -> Cow<'static, str> { format!("no puede tener más de {max} caracteres").into() } fn ascii_invalid(&self) -> Cow<'static, str> { "debe contener solo caracteres ASCII".into() } fn required_not_set(&self) -> Cow<'static, str> { "este campo es obligatorio".into() } fn range_lower_than(&self, min: &dyn std::fmt::Display) -> Cow<'static, str> { format!("debe ser mayor que {min}").into() } fn range_greater_than(&self, max: &dyn std::fmt::Display) -> Cow<'static, str> { format!("debe ser menor que {max}").into() } // ... implement remaining methods fn alphanumeric_invalid(&self) -> Cow<'static, str> { "solo debe contener letras y números".into() } fn email_invalid(&self, _: garde::i18n::InvalidEmail) -> Cow<'static, str> { "correo electrónico inválido".into() } fn url_invalid(&self, _: garde::i18n::InvalidUrl) -> Cow<'static, str> { "URL inválida".into() } fn pattern_no_match(&self, _: &dyn std::fmt::Display) -> Cow<'static, str> { "formato inválido".into() } fn contains_missing(&self, pattern: &dyn std::fmt::Display) -> Cow<'static, str> { format!("debe contener \"{pattern}\"").into() } fn prefix_missing(&self, pattern: &dyn std::fmt::Display) -> Cow<'static, str> { format!("debe comenzar con \"{pattern}\"").into() } fn suffix_missing(&self, pattern: &dyn std::fmt::Display) -> Cow<'static, str> { format!("debe terminar con \"{pattern}\"").into() } fn credit_card_invalid(&self, _: garde::i18n::InvalidCreditCard) -> Cow<'static, str> { "número de tarjeta inválido".into() } fn phone_number_invalid(&self, _: garde::i18n::InvalidPhoneNumber) -> Cow<'static, str> { "número de teléfono inválido".into() } fn ip_invalid(&self, _: garde::i18n::IpKind) -> Cow<'static, str> { "dirección IP inválida".into() } fn matches_field_mismatch(&self, field: &dyn std::fmt::Display) -> Cow<'static, str> { format!("no coincide con el campo {field}").into() } } #[derive(Validate)] struct Form { #[garde(length(min = 3))] name: String, } let form = Form { name: "ab".to_string() }; let result = with_i18n(Spanish, || form.validate()); if let Err(report) = result { // Prints: "debe tener al menos 3 caracteres" println!("{}", report); } ``` -------------------------------- ### Prefix Validation Trait Source: https://github.com/jprochazk/garde/blob/main/_autodocs/types.md Defines a trait for validating if a string starts with a specific prefix pattern. ```rust pub trait Prefix { fn validate_prefix(&self, pattern: &str) -> bool; } ``` -------------------------------- ### Display Path Implementation Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Demonstrates how the Display trait formats Path for human-readable output, using dots for keys and brackets for indices. ```rust impl std::fmt::Display for Path { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { // Renders as "field[0].nested.key[1]" } } use garde::Path; let path = Path::new("users").join(0).join("email"); println!("{}", path); // Output: "users[0].email" ``` -------------------------------- ### Path Display Implementation Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Provides a human-readable string representation of a Path, using dots for keys and brackets for indices. ```APIDOC ## Display Implementation `Path` implements `Display` to render paths in a human-readable format: - Field keys are separated by dots: `user.profile.name` - Array indices use brackets: `items[0].value` ### Example ```rust use garde::Path; let path = Path::new("users").join(0).join("email"); println!("{}", path); // Output: "users[0].email" ``` ``` -------------------------------- ### Path::new Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Creates a new path with a single component, which can be a field name or an index. ```APIDOC ## Path::new ### Description Creates a new path with a single component. ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | `component` | `impl PathComponentKind` | Path component (field name as &str or index as usize) | ### Returns `Path` ### Example ```rust use garde::Path; let path = Path::new("username"); assert_eq!(path.to_string(), "username"); let path = Path::new(0); assert_eq!(path.to_string(), "[0]"); ``` ``` -------------------------------- ### Path::join Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Appends a component to an existing path, returning a new path. ```APIDOC ## Path::join ### Description Appends a component to the path. ### Parameters | Parameter | Type | Description | |-----------|------|-------------| | `component` | `impl PathComponentKind` | Component to append | ### Returns New `Path` with appended component ### Example ```rust use garde::Path; let path = Path::new("users") .join(0) .join("email"); assert_eq!(path.to_string(), "users[0].email"); ``` ``` -------------------------------- ### Create Unvalidated Data Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validate-trait.md Use `Unvalidated::new` to wrap a value that has not yet been validated. This is the starting point before performing any validation checks. ```rust use garde::Unvalidated; #[derive(garde::Validate)] struct User { #[garde(length(min = 1))] name: String, } let unvalidated = Unvalidated::new(User { name: "Bob".to_string(), }); ``` -------------------------------- ### Enable All Non-Platform-Specific Features Source: https://github.com/jprochazk/garde/blob/main/_autodocs/configuration.md Use the 'full' feature flag as a shorthand to enable all non-platform-specific features, including derive, email, url, regex, and unicode. ```toml garde = { version = "0.23", features = ["full"] } ``` -------------------------------- ### Path::len Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Returns the number of components in the path. ```APIDOC ## Path::len ### Description Returns the number of components in the path. ### Returns `usize` ### Example ```rust use garde::Path; let path = Path::new("users").join(0).join("name"); assert_eq!(path.len(), 3); ``` ``` -------------------------------- ### Display Implementation for Report Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Allows a Report to be formatted as a string, showing each error on a new line with its path. ```rust impl std::fmt::Display for Report { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { // Prints each error on its own line: "path: error message" } } ``` ```rust use garde::Validate; #[derive(Validate)] struct User { #[garde(length(min = 3))] username: String, #[garde(email)] email: String, } let user = User { username: "ab".to_string(), email: "notanemail".to_string(), }; if let Err(report) = user.validate() { println!("{}", report); // Output: // username: length is lower than 3 // email: not a valid email: value is missing `@` } ``` -------------------------------- ### Path::empty Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Creates an empty path, representing the root level. ```APIDOC ## Path::empty ### Description Creates an empty path, representing the root level. ### Returns `Path` ### Example ```rust use garde::Path; let path = Path::empty(); assert!(path.is_empty()); ``` ``` -------------------------------- ### Create Empty Path Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Creates an empty path representing the root level. Use when initializing a path. ```rust use garde::Path; let path = Path::empty(); assert!(path.is_empty()); ``` -------------------------------- ### Create Empty Validation Report Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Initializes an empty report to collect validation errors. ```rust pub fn new() -> Self> ``` ```rust use garde::Report; let report = Report::new(); assert!(report.is_empty()); ``` -------------------------------- ### Combine Multiple Rules on a Single Field Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Multiple validation attributes on the same field are AND-ed together. This example shows combining length and ASCII character set validation. ```rust #[derive(Validate)] struct User { #[garde(length(min = 3, max = 20))] #[garde(ascii)] username: String, } // Equivalent to: #[derive(Validate)] struct User2 { #[garde(ascii, length(min = 3, max = 20))] username: String, } ``` -------------------------------- ### Basic Struct Validation with Garde Source: https://github.com/jprochazk/garde/blob/main/README.md Demonstrates how to derive the Validate trait for a struct and perform validation. Ensures username is ASCII with length constraints and password meets a minimum length. ```rust use garde::{Validate, Valid}; #[derive(Validate)] struct User<'a> { #[garde(ascii, length(min=3, max=25))] username: &'a str, #[garde(length(min=15))] password: &'a str, } let user = User { username: "test", password: "not_a_very_good_password", }; if let Err(e) = user.validate() { println!("invalid user: {e}"); } ``` -------------------------------- ### Custom Error Messages with I18n Source: https://github.com/jprochazk/garde/blob/main/README.md Customizes validation error messages by implementing the `I18n` trait. This example shows custom messages for length and email validation in Czech. ```rust,ignore use garde::{Validate, i18n::{I18n, with_i18n}}; struct Czech; impl I18n for Czech { fn length_lower_than(&self, _: usize, min: usize) -> String { format!("musí obsahovat alespoň {min} znaků") } fn email_invalid(&self, error: &str) -> String { format!("email je neplatný, {error}") } // etc. } #[derive(Validate)] struct User { #[garde(length(min = 3))] name: String, #[garde(email)] email: String, } let user = User { name: "Jan Novák".to_string(), email: "invalid-email".to_string(), }; let result = with_i18n(Czech, || user.validate()); ``` -------------------------------- ### Context and Self Access in Validation Rules Source: https://github.com/jprochazk/garde/blob/main/README.md Validation rules can access the context and the struct itself (`self`) if they are in scope. The example demonstrates using context limits for field length validation. ```rust struct Limits { min: usize, max: usize, } struct Config { username: Limits, } #[derive(garde::Validate)] #[garde(context(Config as ctx))] struct User { #[garde(length(min = ctx.username.min, max = ctx.username.max))] username: String, } ``` -------------------------------- ### URL Validation Rule Usage Source: https://github.com/jprochazk/garde/blob/main/_autodocs/configuration.md Shows how to apply the `#[garde(url)]` rule to validate a string as a URL. Ensure the 'url' feature is enabled. ```rust use garde::Validate; #[derive(Validate)] struct Config { #[garde(url)] api_endpoint: String, } ``` -------------------------------- ### Create Path with Single Component Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Creates a new path with a single component, which can be a field name (string) or an index (usize). ```rust use garde::Path; let path = Path::new("username"); assert_eq!(path.to_string(), "username"); let path = Path::new(0); assert_eq!(path.to_string(), "[0]"); ``` -------------------------------- ### Rust: Handle Specific Email Validation Errors Source: https://github.com/jprochazk/garde/blob/main/_autodocs/errors.md Demonstrates how to iterate through validation errors and specifically check for email-related issues, extracting the reason for invalidity. ```rust use garde::{Validate, i18n::InvalidEmail}; if let Err(report) = contact.validate() { for (path, error) in report.iter() { if error.message().contains("not a valid email") { // Extract specific reason from message if error.message().contains("missing `@`") { println!("Email must contain @"); } } } } ``` -------------------------------- ### Enable Email IDN Support in Garde Source: https://github.com/jprochazk/garde/blob/main/_autodocs/configuration.md Extend email validation to support Internationalized Domain Names (IDN) by enabling both 'email' and 'email-idna' features. This adds the 'idna' crate as a dependency. ```toml garde = { version = "0.23", features = ["email", "email-idna"] } ``` -------------------------------- ### Tuple Variant Enum Validation Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Shows how to use the `Validate` derive macro on an enum with tuple variants. This example applies a length validation to a string field within the tuple variant. ```rust #[derive(Validate)] enum Status { Ok(#[garde(length(min = 1))] String), Error(u32), } ``` -------------------------------- ### new Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validate-trait.md Creates a new Unvalidated instance, wrapping a value that has not yet been validated. ```APIDOC ## new ### Description Creates an `Unvalidated`. ### Method `pub fn new(v: T) -> Self` ### Parameters #### Path Parameters - **v** (T) - Required - The value to wrap as unvalidated ### Returns `Self` (which is `Unvalidated`) ### Example ```rust use garde::Unvalidated; #[derive(garde::Validate)] struct User { #[garde(length(min = 1))] name: String, } let unvalidated = Unvalidated::new(User { name: "Bob".to_string(), }); ``` ``` -------------------------------- ### Rust Struct with Unicode Length Validation Source: https://github.com/jprochazk/garde/blob/main/_autodocs/configuration.md Example of using the `#[garde(length(graphemes, min = ..., max = ...))]` attribute to validate the length of a string based on grapheme clusters. ```rust use garde::Validate; #[derive(Validate)] struct Name { #[garde(length(graphemes, min = 1, max = 50))] display_name: String, // Counts user-perceived characters } ``` -------------------------------- ### Serde Deserialization with Validation Source: https://github.com/jprochazk/garde/blob/main/_autodocs/README.md Shows how to derive both `serde::Deserialize` and `Validate` for a struct. This allows for seamless deserialization and validation of incoming requests. ```rust #[derive(serde::Deserialize, Validate)] struct Request { #[garde(length(min = 1))] #[serde(rename = "user_name")] username: String, } let request: Request = serde_json::from_str(json)?; request.validate()?; ``` -------------------------------- ### Conditional Validation with Context and Field Access Source: https://github.com/jprochazk/garde/blob/main/README.md Conditional validation can incorporate both context variables and struct fields in its conditions. This example validates API key length only if in production and it's a service account. ```rust #[derive(garde::Validate)] #[garde(context(Config as ctx))] struct ApiKey { #[garde(if(cond = ctx.production && self.is_service_account, length(min = 32)))] key: String, #[garde(skip)] is_service_account: bool, } struct Config { production: bool, } ``` -------------------------------- ### Comprehensive Length Validations Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md Demonstrates various length validation modes (simple, bytes, graphemes) and constraints (min, max, equal) for different fields including strings and vectors. ```rust use garde::Validate; #[derive(Validate)] struct Account { #[garde(length(min = 3, max = 20))] username: String, #[garde(length(min = 8))] password: String, #[garde(length(bytes, min = 8, max = 255))] bio: String, #[garde(length(graphemes, min = 1, max = 50))] emoji_status: String, #[garde(length(min = 1, max = 100))] tags: Vec, #[garde(length(equal = 16))] code: Vec, } ``` -------------------------------- ### Path::is_empty Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/error-handling.md Checks if the path has no components. ```APIDOC ## Path::is_empty ### Description Returns `true` if the path has no components. ### Returns `bool` ### Example ```rust use garde::Path; assert!(Path::empty().is_empty()); assert!(!Path::new("field").is_empty()); ``` ``` -------------------------------- ### Inner Rule Example Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/validation-rules.md The `inner` rule applies validation rules to the inner types of generic containers like `Vec` or `Option`. It can be nested to apply multiple rules or rules to deeply nested structures. ```rust use garde::Validate; #[derive(Validate)] struct List { #[garde( length(min = 1), inner(ascii, length(min = 1)) )] items: Vec, } ``` ```rust use garde::Validate; #[derive(Validate)] struct Data { // Validates Vec length AND each String's length #[garde( length(min = 1, max = 10), inner(length(min = 1, max = 255)) )] items: Vec, // Validates Option presence AND String content #[garde( required, inner(ascii, length(min = 1)) )] maybe_code: Option, // Deeply nested validation #[garde( length(min = 1), // Vec has items inner(required), // Options are Some inner(inner(ascii)) // Strings are ASCII )] nested: Vec>, } ``` -------------------------------- ### Multiple vs Single Field Attribute Source: https://github.com/jprochazk/garde/blob/main/_autodocs/api-reference/derive-macros.md Demonstrates that applying multiple #[garde(...)] attributes to a field is equivalent to combining them within a single attribute. ```rust // Multiple attributes #[garde(ascii)] #[garde(length(min = 1))] text: String, // Single attribute #[garde(ascii, length(min = 1))] text: String, ```