### Complete Signup Form Example with Custom Validations Source: https://github.com/keats/validator/blob/master/_autodocs/derive-macro.md A comprehensive example demonstrating a `SignupForm` struct with various validation rules, including length, email format, custom functions, password strength, matching fields, required options, and nested validation for an `Address` struct. It also includes a schema-level validation for accepting terms. ```rust use validator::{Validate, ValidationError}; fn validate_password(password: &str) -> Result<(), ValidationError> { if !password.chars().any(|c| c.is_numeric()) { return Err(ValidationError::new("no_digits")); } Ok(()) } #[derive(Validate)] #[validate(schema(function = "validate_signup_dates", skip_on_field_errors = false))] struct SignupForm { #[validate(length(min = 1, max = 100), email)] email: String, #[validate(length(min = 1, max = 50))] username: String, #[validate(length(min = 8, max = 128), custom(function = "validate_password"))] password: String, #[validate(must_match(other = "password"))] confirm_password: String, #[validate(required)] accept_terms: Option, #[validate(nested)] address: Address, } #[derive(Validate)] struct Address { #[validate(length(min = 1))] street: String, #[validate(length(min = 2), regex(path = "COUNTRY_CODE_REGEX"))] country_code: String, } fn validate_signup_dates(form: &SignupForm) -> Result<(), ValidationError> { if !form.accept_terms.unwrap_or(false) { return Err(ValidationError::new("must_accept_terms")); } Ok(()) } ``` -------------------------------- ### Basic Struct Validation Example Source: https://github.com/keats/validator/blob/master/_autodocs/traits.md Demonstrates how to use the `#[derive(Validate)]` macro on a struct and then call the `validate` method. This example shows validation of email format and password length. ```rust use serde::Deserialize; use validator::{Validate, ValidationError}; #[derive(Debug, Validate, Deserialize)] struct SignupData { #[validate(email)] email: String, #[validate(length(min = 8))] password: String, } let data = SignupData { email: "user@example.com".to_string(), password: "securepass123".to_string(), }; match data.validate() { Ok(()) => println!("Validation passed"), Err(errors) => println!("Validation errors: {}", errors), } ``` -------------------------------- ### Example Usage of ValidateLength Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md Shows how to use `validate_length` with minimum, maximum, and exact length constraints on strings and vectors. Unicode characters are counted correctly. ```rust use validator::ValidateLength; assert!("hello".validate_length(Some(1), Some(10), None)); assert!("hello".validate_length(None, None, Some(5))); assert!(!"hello".validate_length(Some(10), None, None)); // too short assert!(vec![1, 2, 3].validate_length(Some(2), Some(5), None)); // Unicode characters counted correctly assert!("日本".validate_length(None, None, Some(2))); // 2 chars, not bytes ``` -------------------------------- ### Install validator Crate Source: https://github.com/keats/validator/blob/master/README.md Add the validator crate with the 'derive' feature to your Cargo.toml file for custom derive support. ```toml [dependencies] validator = { version = "0.20", features = ["derive"] } ``` -------------------------------- ### Rust validate_must_match Usage Example Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md Demonstrates how to use the validate_must_match function with different data types. Ensure the validator crate is imported before use. ```rust use validator::validate_must_match; assert!(validate_must_match("password", "password")); assert!(!validate_must_match("pass1", "pass2")); assert!(validate_must_match(Some(5), Some(5))); ``` -------------------------------- ### Struct-Level Schema Validation Example Source: https://github.com/keats/validator/blob/master/_autodocs/derive-macro.md Example of using `#[validate(schema(function = "..."))]` to apply a custom validation function to an entire struct after field validations. ```rust use validator::{Validate, ValidationError}; fn validate_dates(data: &DateRange) -> Result<(), ValidationError> { if data.start > data.end { return Err(ValidationError::new("date_order")); } Ok(()) } #[derive(Validate)] #[validate(schema(function = "validate_dates"))] struct DateRange { start: String, end: String, } ``` -------------------------------- ### Example Usage of ValidateUrl Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md Demonstrates how to use the `validate_url` method on string slices and `String` objects. Returns true for valid URLs and false for invalid ones. ```rust use validator::ValidateUrl; assert!("https://example.com".validate_url()); assert!("http://localhost:8080/path".validate_url()); assert!("ftp://ftp.example.com/file.txt".validate_url()); assert!(!("not a url".validate_url())); ``` -------------------------------- ### Email Validation Examples Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md Demonstrates how to use the `validate_email` method for various string inputs, including valid and invalid formats, and how `Option` types are handled. The `None` variant of an `Option` is considered valid. ```rust use validator::ValidateEmail; assert!("user@example.com".validate_email()); assert!("test.name+tag@sub.domain.co.uk".validate_email()); assert!(!("invalid.email".validate_email())); assert!(!("user@".validate_email())); assert!(None::<&str>.validate_email()); // Option is valid when None ``` -------------------------------- ### ValidateRange Examples Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md Demonstrates the usage of the validate_range method for inclusive and exclusive bounds, including handling Option values. None values are considered to pass range validation. ```rust use validator::ValidateRange; assert!(5.validate_range(Some(1), Some(10), None, None)); assert!(5.validate_range(Some(5), None, None, None)); // inclusive assert!(!5.validate_range(None, None, Some(5), None)); // exclusive > 5 assert!(5.validate_range(None, None, None, Some(10))); // exclusive < 10 // Option values assert!(Some(5).validate_range(Some(1), Some(10), None, None)); assert!(None::.validate_range(Some(1), Some(10), None, None)); // None passes ``` -------------------------------- ### URL Validation Failures Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Provides examples of strings that are not considered valid URLs by the validator, including malformed or incomplete schemes and invalid characters. ```rust use validator::ValidateUrl; "https://example.com".validate_url() => true "http://localhost:8080".validate_url() => true "ftp://files.example.com".validate_url() => true "not a url".validate_url() => false "http".validate_url() => false "ht!tp://example.com".validate_url() => false ``` -------------------------------- ### Collection Validation Example Source: https://github.com/keats/validator/blob/master/_autodocs/traits.md Shows how the `Validate` trait is automatically implemented for collections like `Vec`. When validating a collection, each item is validated independently, and errors are aggregated. ```rust use validator::Validate; #[derive(Validate)] struct Item { #[validate(email)] email: String, } let items = vec![ Item { email: "valid@example.com".to_string() }, Item { email: "invalid".to_string() }, ]; if let Err(errors) = items.validate() { // Errors at index 1 will be in the "_tmp_validator" field } ``` -------------------------------- ### Example JSON Serialization of ValidationErrorsKind Source: https://github.com/keats/validator/blob/master/_autodocs/types.md Illustrates the JSON output for a nested ValidationErrorsKind structure, showing how 'Field' variants appear as arrays and 'Struct'/'List' variants as nested objects. ```json { "email": [ { "code": "email", "message": null, "params": { "value": "invalid" } } ], "contacts": { "0": { "email": [ { "code": "email", "message": null, "params": { "value": "bad@" } } ] } } } ``` -------------------------------- ### Example Validation Error JSON Structure Source: https://github.com/keats/validator/blob/master/_autodocs/guide.md Illustrates the typical JSON structure of validation errors returned by the validator crate. This format is useful for client-side error handling or logging. ```json { "email": [ { "code": "email", "message": null, "params": { "value": "invalid" } } ], "password": [ { "code": "length", "message": null, "params": { "value": "short", "min": 8 } } ] } ``` -------------------------------- ### Email Validation Failures Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Examples of inputs that will fail email validation due to length, format, or character restrictions. Includes a note on IDN domain handling. ```rust use validator::ValidateEmail; // Too long local part (> 64 characters) "a".repeat(65) + "@example.com" => false // Too long domain (> 255 characters) "user@" + &"a".repeat(256) => false // Missing @ "userexample.com" => false // Invalid domain characters "user@exam ple.com" => false // Missing local or domain "@example.com" => false "user@" => false // IDN domains "user@münchen.de" => true (converted to punycode) ``` -------------------------------- ### Implement ValidateArgs with Context Source: https://github.com/keats/validator/blob/master/_autodocs/traits.md Example of implementing ValidateArgs with a custom validator that uses context. The `#[validate(context = "ValidationContext")]` attribute specifies the context type, and `#[validate(custom(function = "validate_username", use_context))]` applies the custom validator with context. ```rust use validator::{Validate, ValidateArgs, ValidationError}; fn validate_username(name: &str, context: &ValidationContext) -> Result<(), ValidationError> { if context.forbidden_names.contains(&name) { return Err(ValidationError::new("forbidden")); } Ok(()) } pub struct ValidationContext { forbidden_names: Vec, } #[derive(Validate)] #[validate(context = "ValidationContext")] struct SignupForm { #[validate(custom(function = "validate_username", use_context))] username: String, } let form = SignupForm { username: "admin".to_string() }; let context = ValidationContext { forbidden_names: vec!["admin".to_string(), "root".to_string()], }; match form.validate_with_args(&context) { Ok(()) => println!("Valid"), Err(e) => println!("Errors: {}", e), } ``` -------------------------------- ### Credit Card Validation Failures Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Examples of credit card numbers that fail validation due to an invalid Luhn checksum or non-numeric characters. Includes examples of valid card types. ```rust use validator::ValidateCreditCard; // Invalid Luhn checksum "5236313877109141".validate_credit_card() => false // Non-numeric "abcd-efgh-ijkl-mnop".validate_credit_card() => false // Valid cards (examples) "4539571147647251".validate_credit_card() => true // Visa "343380440754432".validate_credit_card() => true // Amex ``` -------------------------------- ### ValidationErrors::new() Source: https://github.com/keats/validator/blob/master/_autodocs/types.md Creates a new, empty ValidationErrors container. This is the starting point for collecting validation errors. ```APIDOC ## ValidationErrors::new() ### Description Creates an empty ValidationErrors container. ### Method `new() -> ValidationErrors` ### Example ```rust use validator::ValidationErrors; let errors = ValidationErrors::new(); assert!(errors.is_empty()); ``` ``` -------------------------------- ### Range Validation Failures Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Examples of values that fail range validation due to being below the minimum, above the maximum, or violating exclusive bounds. Shows combined constraints. ```rust use validator::ValidateRange; // Below minimum 5u32.validate_range(Some(10), None, None, None) => false // Above maximum 15u32.validate_range(None, Some(10), None, None) => false // Exclusive min (must be > not >=) 5.validate_range(None, None, Some(5), None) => false // Exclusive max (must be < not <=) 10.validate_range(None, None, None, Some(10)) => false // Multiple constraints 5.validate_range(Some(0), Some(10), None, None) => true 5.validate_range(None, None, Some(0), Some(10)) => true ``` -------------------------------- ### Enable Nightly Features for Derive Macro Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Activate 'derive_nightly_features' on nightly Rust builds to get improved error messages within the derive macro. This feature includes all 'derive' functionality plus nightly-specific error reporting. ```toml [dependencies] validator = { version = "0.20", features = ["derive_nightly_features"] } ``` -------------------------------- ### Input Validation in Web Handler Source: https://github.com/keats/validator/blob/master/_autodocs/guide.md Validate incoming request data in web handlers to ensure it meets the required criteria before processing. This example shows validation for a `CreatePostRequest` struct. ```rust use validator::Validate; #[derive(Validate)] struct CreatePostRequest { #[validate(length(min = 1, max = 200))] title: String, #[validate(length(min = 1, max = 10000))] body: String, #[validate(url)] featured_image_url: Option, } async fn create_post( request: CreatePostRequest, ) -> Result { request.validate()?; // Handle request } ``` -------------------------------- ### Build and Test Entire Workspace Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Use these commands to compile and run tests for all crates within the validator workspace. ```bash cargo build --workspace ``` ```bash cargo test --workspace ``` -------------------------------- ### Build Individual Crates Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Commands to compile specific crates within the validator workspace. Use the '-p' flag followed by the crate name. ```bash cargo build -p validator ``` ```bash cargo build -p validator_derive ``` -------------------------------- ### Get Reference to Error Map Source: https://github.com/keats/validator/blob/master/_autodocs/types.md Returns an immutable reference to the internal HashMap of validation errors. This map is keyed by field name. ```rust use validator::ValidationErrors; use std::borrow::Cow; let errors = ValidationErrors::new(); let map = errors.errors(); assert_eq!(map.len(), 0); ``` -------------------------------- ### Validator Crate File Layout Source: https://github.com/keats/validator/blob/master/_autodocs/README.md Illustrates the directory and file structure of the validator project, including the core library and the derive macro crate. ```text validator/ ├── Cargo.toml # Workspace definition ├── README.md # Project README ├── validator/ │ ├── Cargo.toml # Core library │ └── src/ │ ├── lib.rs # Entry point, exports │ ├── types.rs # ValidationError/Errors types │ ├── traits.rs # Validate trait │ ├── display_impl.rs # Error formatting │ └── validation/ │ ├── mod.rs │ ├── email.rs │ ├── urls.rs │ ├── length.rs │ ├── range.rs │ ├── contains.rs │ ├── does_not_contain.rs │ ├── regex.rs │ ├── cards.rs │ ├── ip.rs │ ├── required.rs │ ├── non_control_character.rs │ └── must_match.rs ├── validator_derive/ │ ├── Cargo.toml # Macro crate │ └── src/ │ ├── lib.rs # Macro entry point │ ├── types.rs # Derive input types │ ├── utils.rs # Utilities │ └── tokens/ # Code generation │ ├── mod.rs │ ├── email.rs │ ├── url.rs │ ├── length.rs │ ├── range.rs │ ├── contains.rs │ ├── does_not_contain.rs │ ├── regex.rs │ ├── cards.rs │ ├── ip.rs │ ├── required.rs │ ├── non_control_character.rs │ ├── must_match.rs │ ├── custom.rs │ ├── nested.rs │ └── schema.rs └── validator_derive_tests/ └── tests/ # Integration tests ``` -------------------------------- ### Get Mutable Reference to Error Map Source: https://github.com/keats/validator/blob/master/_autodocs/types.md Returns a mutable reference to the internal HashMap of validation errors, allowing for direct manipulation of the error map. ```rust use validator::{ValidationErrors, ValidationError, ValidationErrorsKind}; use std::borrow::Cow; let mut errors = ValidationErrors::new(); let field_error = ValidationError::new("email"); let mut errors_mut = errors.errors_mut(); errors_mut.insert( Cow::Borrowed("email_field"), ValidationErrorsKind::Field(vec![field_error]) ); ``` -------------------------------- ### Static Regex Pattern with OnceLock Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Alternatively, use `std::sync::OnceLock` to define static regex patterns. The `get_or_init` method ensures the regex is compiled only once when first accessed. ```rust use std::sync::OnceLock; use regex::Regex; static PASSWORD_RE: OnceLock = OnceLock::new(); fn get_password_re() -> &'static Regex { PASSWORD_RE.get_or_init(|| { Regex::new(r"^(?=.*[A-Z])(?=.*[0-9]).{8,}$").unwrap() }) } #[derive(Validate)] struct Form { #[validate(regex(path = "USERNAME_RE"))] username: String, #[validate(regex(path = "get_password_re()") )] password: String, } ``` -------------------------------- ### Integrate with Indexmap Crate Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md If the 'indexmap' crate is present in your dependencies, the `ValidateLength` trait will automatically support `IndexSet` and `IndexMap`. No specific feature flag is needed for this integration. ```toml [dependencies] validator = "0.20" indexmap = "2" ``` -------------------------------- ### Validate Struct Instance Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Create an instance of your validated struct and call the `validate()` method. Handle the `Result` to check for validation errors. ```rust let user = UserForm { email: "user@example.com".to_string(), username: "john_doe".to_string(), }; match user.validate() { Ok(()) => println!("Valid!"), Err(errors) => println!("Errors: {}", errors), } ``` -------------------------------- ### Configure IP Address Validation Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Use the `#[validate(ip = "ipv4")]` or `#[validate(ip = "ipv6")]` attributes for specific IP versions, or `#[validate(ip)]` for any valid IP format. ```rust #[derive(Validate)] struct NetworkConfig { #[validate(ip = "ipv4")] ipv4_address: String, #[validate(ip = "ipv6")] ipv6_address: String, #[validate(ip)] any_ip: String, } ``` -------------------------------- ### Multiple Field Errors Structure Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Shows how multiple validation errors within a single struct are reported. Each field with an error gets its own entry in the error object. ```rust #[derive(Validate)] struct Form { #[validate(email)] email: String, #[validate(length(min = 8))] password: String, } // Multiple errors: // { // "email": [ // { "code": "email", ... } // ], // "password": [ // { "code": "length", ... } // ] // } ``` -------------------------------- ### URL Validation with Derive Macro Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Use the `#[derive(Validate)]` macro with the `url` attribute for validating URLs. The field should be a `String`. ```rust #[derive(Validate)] struct Config { #[validate(url)] endpoint: String, } ``` -------------------------------- ### Validator Methods Reference Source: https://github.com/keats/validator/blob/master/_autodocs/README.md A table summarizing common validator methods and their signatures. These are typically used with the derive macro. ```rust Email | `validate_email()` | `&self -> bool` ``` ```rust URL | `validate_url()` | `&self -> bool` ``` ```rust Length | `validate_length()` | `&self, min: Option, max: Option, equal: Option -> bool` ``` ```rust Range | `validate_range()` | `&self, min: Option, max: Option, exclusive_min: Option, exclusive_max: Option -> bool` ``` ```rust Contains | `validate_contains()` | `&self, needle: &str -> bool` ``` ```rust Does Not Contain | `validate_does_not_contain()` | `&self, needle: &str -> bool` ``` ```rust Regex | `validate_regex()` | `&self, regex: impl AsRegex -> bool` ``` ```rust Credit Card | `validate_credit_card()` | `&self -> bool` ``` ```rust IP | `validate_ip()` | `&self -> bool` ``` ```rust IP (v4) | `validate_ipv4()` | `&self -> bool` ``` ```rust IP (v6) | `validate_ipv6()` | `&self -> bool` ``` ```rust Required | `validate_required()` | `&self -> bool` ``` ```rust Non-Control Char | `validate_non_control_character()` | `&self -> bool` ``` ```rust Must Match | `validate_must_match()` | `(a: T, b: T) -> bool` ``` -------------------------------- ### Get Field-Level Errors Source: https://github.com/keats/validator/blob/master/_autodocs/types.md Returns a HashMap containing only field-level errors, excluding nested struct or list errors. This is useful for filtering and focusing on direct field validation issues. ```rust use validator::{ValidationErrors, ValidationError, ValidationErrorsKind}; use std::borrow::Cow; let mut errors = ValidationErrors::new(); let field_error = ValidationError::new("email"); errors.0.insert( Cow::Borrowed("email"), ValidationErrorsKind::Field(vec![field_error]) ); let field_errors = errors.field_errors(); assert_eq!(field_errors.len(), 1); ``` -------------------------------- ### Add Validator Dependency Source: https://github.com/keats/validator/blob/master/_autodocs/guide.md Add the validator crate and serde for serialization/deserialization to your Cargo.toml file. Ensure the 'derive' feature is enabled for the validator crate. ```toml [dependencies] validator = { version = "0.20", features = ["derive"] } serde = { version = "1", features = ["derive"] } serde_json = "1" ``` -------------------------------- ### IP Address Validation Failures Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Illustrates inputs that fail IPv4 and IPv6 validation, including out-of-range octets, incomplete addresses, invalid characters, and incorrect formatting. ```rust use validator::ValidateIp; // Valid IPv4 "192.168.1.1".validate_ipv4() => true "127.0.0.1".validate_ipv4() => true "0.0.0.0".validate_ipv4() => true // Invalid IPv4 "256.1.1.1".validate_ipv4() => false // out of range "192.168.1".validate_ipv4() => false // incomplete "192.168.1.1.1".validate_ipv4() => false // too many octets // Valid IPv6 "fe80::1".validate_ipv6() => true "2001:db8::1".validate_ipv6() => true "::1".validate_ipv6() => true // Invalid IPv6 "gggg::1".validate_ipv6() => false // invalid hex "::ffff:999.0.0.1".validate_ipv6() => false // invalid IPv4 part ``` -------------------------------- ### Custom Validator with Immutable Context Source: https://github.com/keats/validator/blob/master/_autodocs/derive-macro.md Demonstrates using `#[validate(context = "...")]` and `#[validate(custom(function = "...", use_context))]` for custom field validators that require an immutable context, such as a database connection. ```rust use validator::{Validate, ValidationError}; struct Database; fn check_email(email: &str, db: &Database) -> Result<(), ValidationError> { // read from db Ok(()) } #[derive(Validate)] #[validate(context = "Database")] struct Form { #[validate(custom(function = "check_email", use_context))] email: String, } let form = Form { email: "test@example.com".to_string() }; let db = Database; form.validate_with_args(&db)?; ``` -------------------------------- ### Validate URL Format Source: https://github.com/keats/validator/blob/master/README.md Use this validator to check if a string is a valid URL. It does not take any arguments. ```rust #[validate(url)] ``` -------------------------------- ### Static Regex Pattern with LazyLock Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Define regex patterns in static variables using `std::sync::LazyLock` for thread-safe, on-demand initialization. This is recommended for Rust 1.80+ and avoids repeated regex compilation. ```rust use regex::Regex; use std::sync::LazyLock; static USERNAME_RE: LazyLock = LazyLock::new(|| { Regex::new(r"^[a-zA-Z0-9_]{3,20}$").unwrap() }); #[derive(Validate)] struct Form { #[validate(regex(path = "USERNAME_RE"))] username: String, #[validate(regex(path = "get_password_re()") )] password: String, } ``` -------------------------------- ### Length Validation Failures Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Demonstrates inputs that fail length validation based on minimum, maximum, or exact length constraints. Highlights Unicode character counting. ```rust use validator::ValidateLength; // Min constraint "hi".validate_length(Some(5), None, None) => false // Max constraint "verylongstring".validate_length(None, Some(5), None) => false // Equal constraint overrides min/max "hello".validate_length(Some(1), Some(2), Some(5)) => true // The equal = 5 takes precedence // Unicode characters "日本".validate_length(None, None, Some(2)) => true // Counted as 2 characters, not bytes ``` -------------------------------- ### Regex Validation Failures Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Shows inputs that fail regex validation against a pattern requiring only lowercase letters. Demonstrates case sensitivity and digit rejection. ```rust use validator::ValidateRegex; use regex::Regex; let re = Regex::new(r"^[a-z]+$").unwrap(); "hello".validate_regex(&re) => true "Hello".validate_regex(&re) => false // uppercase "hello123".validate_regex(&re) => false // digits ``` -------------------------------- ### Context-Aware Validation Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Enable context-aware validation using the `context` attribute on the struct and `use_context` with the `custom` attribute for functions. Validation requires calling `validate_with_args`. ```rust #[derive(Validate)] #[validate(context = "Database")] struct SignupForm { #[validate(custom(function = "check_unique", use_context))] email: String, } form.validate_with_args(&db)?; ``` -------------------------------- ### Option and Collection Validation Behavior Source: https://github.com/keats/validator/blob/master/_autodocs/derive-macro.md Understand how `Option` and collection types are validated. `Option` fields are validated only when `Some`. Collections like `Vec` are fully validated, and `Option>` validates the collection if it's `Some`. ```rust #[derive(Validate)] struct Data { #[validate(email)] primary_email: String, #[validate(email)] // Only validated if Some backup_email: Option, #[validate(nested)] // Each item validated addresses: Vec
, #[validate(nested)] // Items validated only if Some optional_addresses: Option>, } ``` -------------------------------- ### Convert to Regex Object Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md Provides a trait for types that can be converted into a Regex object. This is useful for abstracting over different regex initialization patterns. ```rust use validator::AsRegex; use regex::Regex; use std::sync::LazyLock; // Example usage would involve calling as_regex() on types that implement it, // such as LazyLock, &OnceLock, etc. // The trait itself defines the conversion mechanism. ``` -------------------------------- ### Handle Empty Option Fields Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Fields of type `Option` are considered valid when `None` by default. Use `#[validate(required)]` to enforce that these fields must have a value. ```rust #[derive(Validate)] struct Form { #[validate(email)] optional_email: Option, // Valid if None #[validate(required)] required_option: Option, // Invalid if None } ``` -------------------------------- ### Validate IP Address Formats with Trait Methods Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md The `ValidateIp` trait provides convenient methods like `validate_ipv4()`, `validate_ipv6()`, and `validate_ip()` for direct string validation. ```rust use validator::ValidateIp; assert!("192.168.1.1".validate_ipv4()); assert!("fe80::1".validate_ipv6()); assert!("192.168.1.1".validate_ip()); ``` -------------------------------- ### IP Address Validation using Trait Methods Source: https://github.com/keats/validator/blob/master/_autodocs/guide.md Validate IP addresses directly using the `ValidateIp` trait methods. This provides convenient checks for IPv4, IPv6, or any valid IP format. ```Rust use validator::{Validate, ValidateIp}; #[derive(Validate)] struct NetworkConfig { #[validate(length(min = 1))] name: String, } // Using trait methods directly let ipv4 = "192.168.1.1"; assert!(ipv4.validate_ipv4()); assert!(!ipv4.validate_ipv6()); assert!(ipv4.validate_ip()); ``` -------------------------------- ### Custom Validator with Mutable Context Source: https://github.com/keats/validator/blob/master/_autodocs/derive-macro.md Shows how to use `#[validate(context = "...", mutable)]` for custom field validators that need mutable access to the context, allowing for state changes during validation. ```rust use validator::{Validate, ValidationError}; struct Database; fn check_email(email: &str, db: &mut Database) -> Result<(), ValidationError> { // mutate db Ok(()) } #[derive(Validate)] #[validate(context = "Database<'v_a>", mutable)] struct Form { #[validate(custom(function = "check_email", use_context))] email: String, } let form = Form { email: "test@example.com".to_string() }; let mut db = Database; form.validate_with_args(&mut db)?; ``` -------------------------------- ### Basic Struct with Email Validation Source: https://github.com/keats/validator/blob/master/_autodocs/derive-macro.md Apply the `#[derive(Validate)]` macro to a struct and use field attributes like `#[validate(email)]` for built-in validations. ```rust use validator::Validate; #[derive(Validate)] struct MyStruct { #[validate(email)] email: String, } ``` -------------------------------- ### ValidateArgs for Option Source: https://github.com/keats/validator/blob/master/_autodocs/traits.md Shows the implementation of ValidateArgs for `Option`, where `T` must also implement `ValidateArgs`. The validation logic is only applied if the option contains a `Some` value. ```rust use validator::ValidateArgs; let some_value: Option = Some("test@example.com".to_string()); let result = some_value.validate_with_args(()); ``` -------------------------------- ### Basic Custom Validation Function Reference Source: https://github.com/keats/validator/blob/master/README.md Reference a custom validation function by its path. The function should return a Result<(), ValidationError>. ```rust #[validate(custom(function = "validate_something"))] #[validate(custom(function = "::utils::validate_something"))] ``` -------------------------------- ### Length Validation with Derive Macro Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Use the `#[derive(Validate)]` macro with the `length` attribute to enforce minimum and maximum lengths for a `String` field. Specify `min` and `max` values. ```rust #[derive(Validate)] struct Form { #[validate(length(min = 8, max = 100))] password: String, } ``` -------------------------------- ### Context-Aware Custom Validation Source: https://github.com/keats/validator/blob/master/_autodocs/README.md Perform custom validation that requires external context, such as a database connection, using `#[validate(custom(function = "...", use_context))]` and passing the context to `validate_with_args()`. ```rust #[derive(Validate)] #[validate(context = "Database")] struct Form { #[validate(custom(function = "check_exists", use_context))] email: String, } form.validate_with_args(&db)?; ``` -------------------------------- ### Default Error Message Display Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Demonstrates how validation errors are displayed with field paths and default messages. This is useful for understanding the structure of validation failures. ```rust #[derive(Validate)] struct Signup { #[validate(email)] email: String, #[validate(length(min = 8))] password: String, } let data = Signup { email: "invalid".to_string(), password: "short".to_string(), }; println!("{}", data.validate().unwrap_err()); // Output: // email: Validation error: email [...] // password: Validation error: length [...] ``` -------------------------------- ### Create an Empty ValidationErrors Container Source: https://github.com/keats/validator/blob/master/_autodocs/types.md Creates a new, empty ValidationErrors container. Use this to initialize a validation error collection. ```rust use validator::ValidationErrors; let errors = ValidationErrors::new(); assert!(errors.is_empty()); ``` -------------------------------- ### Converting Errors to JSON for API Response Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Use `serde_json::json!` to create a JSON object representing validation errors for API responses. Ensure `serde_json` is imported. ```Rust use serde_json::json; if let Err(errors) = data.validate() { let response = json!({ "success": false, "errors": errors, }); // Send as HTTP response } ``` -------------------------------- ### Import Trait for Email Validation Source: https://github.com/keats/validator/blob/master/_autodocs/guide.md Import the `ValidateEmail` trait before using its methods on String types to avoid compiler errors. ```rust use validator::ValidateEmail; // Add this let email = "test@example.com".to_string(); assert!(email.validate_email()); ``` -------------------------------- ### Email Validation with Derive Macro Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Use the `#[derive(Validate)]` macro with the `email` attribute for validating email addresses. Ensure the field is of type `String`. ```rust #[derive(Validate)] struct Form { #[validate(email)] email: String, } ``` -------------------------------- ### Configure String Length Validation Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Empty strings are only considered invalid if a `min` length greater than 0 is specified. The `max` length constraint does not cause empty strings to fail. ```rust #[derive(Validate)] struct Form { #[validate(length(min = 1))] required_field: String, // Empty string fails #[validate(length(max = 100))] optional_field: String, // Empty string passes #[validate(email)] email: String, // Empty string fails (invalid email) } ``` -------------------------------- ### Validator Crate Module Exports Source: https://github.com/keats/validator/blob/master/_autodocs/INDEX.md Lists all public types and traits exported from the validator crate. These are the core components available for use in your project. ```rust ValidationError ValidationErrors ValidationErrorsKind Validate ValidateArgs ValidateEmail ValidateUrl ValidateLength ValidateRange ValidateContains ValidateDoesNotContain ValidateRegex AsRegex ValidateCreditCard ValidateRequired ValidateNonControlCharacter ValidateIp validate_must_match ``` -------------------------------- ### Define Struct with Validation Rules Source: https://github.com/keats/validator/blob/master/_autodocs/guide.md Use the `#[derive(Validate)]` macro to automatically implement validation for your struct fields. Apply built-in validation attributes like `email`, `length`, and `must_match` to specific fields. ```rust use validator::Validate; use serde::{Serialize, Deserialize}; #[derive(Debug, Serialize, Deserialize, Validate)] struct UserSignup { #[validate(email)] email: String, #[validate(length(min = 3, max = 30))] username: String, #[validate(length(min = 8))] password: String, #[validate(must_match(other = "password"))] confirm_password: String, } ``` -------------------------------- ### ValidateIp Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md Validates IPv4 and IPv6 addresses. Provides methods to check for valid IPv4, IPv6, or either format. ```APIDOC ## ValidateIp ### Description Validates IPv4 and IPv6 addresses. ### Methods #### `validate_ipv4(&self) -> bool` Returns true if the value is a valid IPv4 address. **Example:** ```rust use validator::ValidateIp; assert!("192.168.1.1".validate_ipv4()); assert!("127.0.0.1".validate_ipv4()); assert!(!"256.1.1.1".validate_ipv4()); // out of range ``` #### `validate_ipv6(&self) -> bool` Returns true if the value is a valid IPv6 address. **Example:** ```rust use validator::ValidateIp; assert!("fe80::1".validate_ipv6()); assert!( "::1".validate_ipv6()); assert!("2001:db8::1".validate_ipv6()); assert!(!"gggg::1".validate_ipv6()); // invalid hex ``` #### `validate_ip(&self) -> bool` Returns true if the value is valid IPv4 or IPv6. **Example:** ```rust use validator::ValidateIp; assert!("192.168.1.1".validate_ip()); assert!("fe80::1".validate_ip()); assert!(!"not an ip".validate_ip()); ``` ``` -------------------------------- ### Default Args Type for ValidateArgs Source: https://github.com/keats/validator/blob/master/_autodocs/traits.md Illustrates the default `Args = ()` implementation for ValidateArgs when no custom validators use `use_context`. This simplifies calling `validate_with_args` with an empty tuple. ```rust use validator::{Validate, ValidateArgs}; #[derive(Validate)] struct SimpleForm { #[validate(email)] email: String, } let form = SimpleForm { email: "test@example.com".to_string() }; // Args type is (), so calling with () works let result = form.validate_with_args(()); assert!(result.is_ok()); ``` -------------------------------- ### Calling .validate() on an Instance Source: https://github.com/keats/validator/blob/master/_autodocs/derive-macro.md After applying the derive macro, you can call the `.validate()` method on struct instances to check their validity. It returns a `Result` indicating success or a collection of errors. ```rust let data = MyStruct { email: "user@example.com".to_string() }; match data.validate() { Ok(()) => println!("Valid"), Err(errors) => println!("Errors: {}", errors), } ``` -------------------------------- ### Regex Validation with LazyLock for Efficiency Source: https://github.com/keats/validator/blob/master/_autodocs/guide.md Use `std::sync::LazyLock` to initialize a `Regex` object once and reuse it for validating string fields against a pattern. This is efficient for frequently used regular expressions. ```Rust use regex::Regex; use std::sync::LazyLock; use validator::Validate; static VALID_SLUG: LazyLock = LazyLock::new(|| { Regex::new(r"^[a-z0-9]+(?:-[a-z0-9]+)*$").unwrap() }); #[derive(Validate)] struct BlogPost { #[validate(regex(path = "VALID_SLUG"))] slug: String, } ``` -------------------------------- ### ValidateUrl Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md Validates whether a string is a valid URL using the `url` crate's parser. It supports various standard URL schemes. ```APIDOC ## ValidateUrl ### Description Validates whether a string is a valid URL using the `url` crate's parser. It supports various standard URL schemes like http, https, ftp, ws, wss, and others. ### Methods #### `validate_url(&self) -> bool` Returns true if the value is a valid URL. **Supported Schemes:** - `http`, `https`, `ftp`, `ws`, `wss`, and other standard URL schemes **Example:** ```rust use validator::ValidateUrl; assert!("https://example.com".validate_url()); assert!(!("not a url".validate_url())); ``` ``` -------------------------------- ### Handle Validation Errors Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Use a match statement to handle the result of a validation. The Ok variant indicates success, while the Err variant contains error details that can be inspected. ```rust match data.validate() { Ok(()) => { // All fields valid } Err(errors) => { // errors.errors() → HashMap of field errors // errors.field_errors() → Only direct field errors // serde_json::to_string(&errors) → JSON output } } ``` -------------------------------- ### IP Address Validator Attribute Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Use `#[validate(ipv4)]` or `#[validate(ipv6)]` to validate if a string is a valid IPv4 or IPv6 address, respectively. ```rust #[validate(ipv4)] ``` ```rust #[validate(ipv6)] ``` -------------------------------- ### Handle Validation Results Source: https://github.com/keats/validator/blob/master/_autodocs/README.md Process the `Result` returned by `validate()`. Use a `match` statement to distinguish between `Ok(())` for valid data and `Err(errors)` for invalid data, iterating through the errors. ```rust match data.validate() { Ok(()) => println!("Valid"), Err(errors) => { for (field, kind) in errors.errors() { println!("Field {}: {:?}", field, kind); } } } ``` -------------------------------- ### Range Validation with Derive Macro Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Use the `#[derive(Validate)]` macro with the `range` attribute to validate numeric fields against minimum and maximum values. Supports integer types like `u32`. ```rust #[derive(Validate)] struct Form { #[validate(range(min = 18, max = 120))] age: u32, } ``` -------------------------------- ### Validate Regex Match Source: https://github.com/keats/validator/blob/master/README.md Use this validator to check if a string matches a given regular expression. It requires a static Regex instance path as an argument. ```rust use regex::Regex; use std::sync::LazyLock; static RE_TWO_CHARS: LazyLock = LazyLock::new(|| { Regex::new(r"[a-z]{2}$").unwrap() }); #[validate(regex(path = *RE_TWO_CHARS))] ``` -------------------------------- ### Validate Email Format Source: https://github.com/keats/validator/blob/master/README.md Use this validator to check if a string is a valid email address according to the HTML5 specification. It does not take any arguments. ```rust #[validate(email)] ``` -------------------------------- ### Create a New ValidationError Source: https://github.com/keats/validator/blob/master/_autodocs/types.md Instantiates a `ValidationError` with a specific error code. The message and parameters are initially empty. ```rust use validator::ValidationError; let error = ValidationError::new("email"); assert_eq!(error.code, "email"); assert_eq!(error.message, None); ``` -------------------------------- ### ValidationError::new Source: https://github.com/keats/validator/blob/master/_autodocs/types.md Creates a new ValidationError with the given code. The message and parameters are initialized as empty. ```APIDOC ## ValidationError::new ### Description Creates a new ValidationError with the given code. Message and params are empty. ### Signature `new(code: &'static str) -> ValidationError` ### Example ```rust use validator::ValidationError; let error = ValidationError::new("email"); assert_eq!(error.code, "email"); assert_eq!(error.message, None); ``` ``` -------------------------------- ### Define Struct with Validation Attributes Source: https://github.com/keats/validator/blob/master/_autodocs/00-START-HERE.md Use the `#[derive(Validate)]` macro and validation attributes like `#[validate(email)]` and `#[validate(length(min = 3, max = 30))]` to define validation rules for struct fields. ```rust use validator::Validate; #[derive(Validate)] struct UserForm { #[validate(email)] email: String, #[validate(length(min = 3, max = 30))] username: String, } ``` -------------------------------- ### Custom Error Message Display Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Shows how to define custom error messages for specific validation rules, providing more user-friendly feedback. Ensure the custom message is correctly formatted within the attribute. ```rust #[derive(Validate)] struct Form { #[validate(email(message = "Invalid email address"))] email: String, } println!("{}", data.validate().unwrap_err()); // Output: // email: Invalid email address ``` -------------------------------- ### Basic String Validation Source: https://github.com/keats/validator/blob/master/_autodocs/README.md Use the `#[validate(email)]` attribute for basic email format validation on String fields. Ensure the struct derives `Validate` and call the `validate()` method. ```rust #[derive(Validate)] struct Form { #[validate(email)] email: String, } form.validate()?; ``` -------------------------------- ### ValidateIp Trait for Any IP Source: https://github.com/keats/validator/blob/master/_autodocs/validators.md This method checks if a string is either a valid IPv4 or IPv6 address. It returns true if the string conforms to either IP format. ```rust use validator::ValidateIp; assert!("192.168.1.1".validate_ip()); assert!("fe80::1".validate_ip()); assert!(!"not an ip".validate_ip()); ``` -------------------------------- ### Struct-Level Context Configuration Source: https://github.com/keats/validator/blob/master/_autodocs/configuration.md Configure the context type for custom validators at the struct level using the `context` attribute. This is useful when your custom validation logic requires external data or state. ```rust #[derive(Validate)] #[validate(context = "Database")] struct Form { #[validate(custom(function = "check_field", use_context))] field: String, } ``` -------------------------------- ### Must Match Validation Failures Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Illustrates scenarios where the `validate_must_match` function returns false, including non-matching strings and mismatched optional values. ```rust use validator::validate_must_match; // Strings don't match validate_must_match("password1", "password2") => false // Option mismatch validate_must_match(Some(5), Some(6)) => false validate_must_match(Some(5), None) => false validate_must_match(None, Some(5)) => false // Both None match validate_must_match(None::, None) => true ``` -------------------------------- ### Struct-Level Derive Macro Attributes Source: https://github.com/keats/validator/blob/master/_autodocs/README.md Attributes that can be applied at the struct level to configure validation behavior. These include schema validation and context definition. ```rust #[validate(schema(function = "validate_fn"))] ``` ```rust #[validate(schema(function = "validate_fn", skip_on_field_errors = false))] ``` ```rust #[validate(context = "Type")] ``` ```rust #[validate(context = "Type<'v_a>", mutable)] ``` -------------------------------- ### Custom Function Validation Source: https://github.com/keats/validator/blob/master/_autodocs/README.md Implement custom validation logic by referencing a function using `#[validate(custom(function = "..."))]`. The specified function must exist and accept the field's type. ```rust #[derive(Validate)] struct Form { #[validate(custom(function = "validate_username"))] username: String, } ``` -------------------------------- ### Email Validation Error Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md Create an email validation error with a specific error code and add parameters. ```rust let email = "invalid"; let mut error = ValidationError::new("email"); error.add_param(Cow::Borrowed("value"), &email); // Serializes to: // { // "code": "email", // "message": null, // "params": { "value": "invalid" } // } ``` -------------------------------- ### Checking for Specific Field Errors Source: https://github.com/keats/validator/blob/master/_autodocs/errors.md After validation fails, check if specific fields like 'email' or 'password' have errors using `errors.errors().contains_key()`. This allows for targeted user feedback. ```Rust if let Err(errors) = data.validate() { if errors.errors().contains_key("email") { eprintln!("Email validation failed"); } if errors.errors().contains_key("password") { eprintln!("Password validation failed"); } } ``` -------------------------------- ### Define and Use Custom Validation Function Source: https://github.com/keats/validator/blob/master/_autodocs/guide.md Create custom validation logic by defining a function that returns `Result<(), ValidationError>`. Apply this function to a field using the `custom` attribute, optionally with arguments. ```rust use validator::{Validate, ValidationError}; fn validate_strong_password(password: &str) -> Result<(), ValidationError> { let has_uppercase = password.chars().any(|c| c.is_uppercase()); let has_lowercase = password.chars().any(|c| c.is_lowercase()); let has_digit = password.chars().any(|c| c.is_numeric()); let has_special = password.chars().any(|c| !c.is_alphanumeric()); if !(has_uppercase && has_lowercase && has_digit && has_special) { return Err(ValidationError::new("weak_password")); } Ok(()) } #[derive(Validate)] struct SecureForm { #[validate( length(min = 12), custom(function = "validate_strong_password") )] password: String, } ``` -------------------------------- ### URL Validation Source: https://github.com/keats/validator/blob/master/_autodocs/derive-macro.md Validates that a string is a valid URL. Supports custom error codes. ```rust #[derive(Validate)] struct Config { #[validate(url)] api_endpoint: String, #[validate(url(code = "invalid_url"))] webhook_url: String, } ```