### Installation Source: https://docs.rs/validator/0.20.0/src/validator/lib.rs.html Instructions on how to add the validator crate to your project's Cargo.toml file. ```APIDOC ## Installation ### Description To use the `validator` crate in your Rust project, add it as a dependency in your `Cargo.toml` file. It is recommended to enable the `derive` feature for using the `#[derive(Validate)]` macro. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example ```toml [dependencies] validator = { version = "0.16", features = ["derive"] } ``` ### Response N/A ``` -------------------------------- ### Validator Crate Usage Example Source: https://docs.rs/validator/0.20.0/src/validator/lib.rs.html An example demonstrating how to use the `Validate` derive macro for struct validation, including custom validation functions. ```APIDOC ## Example: Struct Validation with Derive Macro ### Description This example shows how to use the `#[derive(Validate)]` macro to automatically implement the `Validate` trait for a struct. It includes various built-in validation attributes like `email`, `url`, `length`, and `range`, as well as a custom validation function. ### Method N/A (This is a code example, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```rust use serde::Deserialize; use validator::{Validate, ValidationError}; #[derive(Debug, Validate, Deserialize)] struct SignupData { #[validate(email)] mail: String, #[validate(url)] site: String, #[validate(length(min = 1), custom(function = "validate_unique_username"))] #[serde(rename = "firstName")] first_name: String, #[validate(range(min = 18, max = 20))] age: u32, } fn validate_unique_username(username: &str) -> Result<(), ValidationError> { if username == "xXxShad0wxXx" { return Err(ValidationError::new("terrible_username")); } Ok(()) } // Usage within a function: // let signup_data = SignupData { ... }; // match signup_data.validate() { // Ok(_) => println!("Validation successful!"), // Err(e) => println!("Validation failed: {:?}", e), // }; ``` ### Response N/A (This is a code example) ### Error Handling - The `validate()` method returns a `Result`. On success, it returns `Ok(())`. On failure, it returns `Err(ValidationError)` or `Err(ValidationErrors)` if multiple errors occur. ``` -------------------------------- ### Install validator dependency Source: https://docs.rs/validator/0.20.0/index.html Add the validator crate to your Cargo.toml file with the derive feature enabled. ```toml [dependencies] validator = { version = "0.16", features = ["derive"] } ``` -------------------------------- ### Struct Validation with Derive Macro Source: https://docs.rs/validator/0.20.0/validator/index.html Use the `Validate` derive macro to automatically implement validation logic for your structs. This example demonstrates various built-in validations like email, URL, length, range, and a custom function. Ensure the `serde` crate is also included if deserialization is needed. ```rust use serde::Deserialize; // A trait that the Validate derive will impl use validator::{Validate, ValidationError}; #[derive(Debug, Validate, Deserialize)] struct SignupData { #[validate(email)] mail: String, #[validate(url)] site: String, #[validate(length(min = 1), custom(function = "validate_unique_username"))] #[serde(rename = "firstName")] first_name: String, #[validate(range(min = 18, max = 20))] age: u32, } fn validate_unique_username(username: &str) -> Result<(), ValidationError> { if username == "xXxShad0wxXx" { // the value of the username will automatically be added later return Err(ValidationError::new("terrible_username")); } Ok(()) } match signup_data.validate() { Ok(_) => (), Err(e) => return e; }; ``` -------------------------------- ### Implement CloneToUninit for T (Nightly) Source: https://docs.rs/validator/0.20.0/validator/enum.ValidationErrorsKind.html An experimental nightly-only API that performs copy-assignment from a value to uninitialized memory. Use with caution. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### as_url_string Method Implementation for &str Source: https://docs.rs/validator/0.20.0/validator/trait.ValidateUrl.html Implementation of the `as_url_string` method for string slices (`&str`). It returns an `Option` containing a `Cow<'_, str>` representation of the URL string. ```rust fn as_url_string(&self) -> Option> ``` -------------------------------- ### Generic Implementations Source: https://docs.rs/validator/0.20.0/validator/struct.ValidationErrors.html Details on blanket implementations for various standard traits. ```APIDOC ## impl Any for T ### Description Provides runtime type information for types that are `'static`. ### Methods - **type_id(&self) -> TypeId**: Gets the `TypeId` of `self`. ## impl Borrow for T ### Description Allows immutable borrowing of a value by reference. ### Methods - **borrow(&self) -> &T**: Immutably borrows from an owned value. ## impl BorrowMut for T ### Description Allows mutable borrowing of a value by reference. ### Methods - **borrow_mut(&mut self) -> &mut T**: Mutably borrows from an owned value. ## impl CloneToUninit for T ### Description Nightly-only experimental API for performing copy-assignment to uninitialized memory. ### Methods - **unsafe fn clone_to_uninit(&self, dest: *mut u8)**: Performs copy-assignment from `self` to `dest`. ## impl From for T ### Description Provides a way to create a value of type `T` from another value of type `T`. ### Methods - **fn from(t: T) -> T**: Returns the argument unchanged. ## impl Into for T ### Description Provides a way to convert a value of type `T` into a value of type `U`, where `U` implements `From`. ### Methods - **fn into(self) -> U**: Calls `U::from(self)`. ## impl ToOwned for T ### Description Provides a way to create an owned version of a borrowed value, typically by cloning. ### Associated Types - **Owned = T**: The resulting type after obtaining ownership. ### Methods - **fn to_owned(&self) -> T**: Creates owned data from borrowed data, usually by cloning. - **fn clone_into(&self, target: &mut T)**: Uses borrowed data to replace owned data, usually by cloning. ## impl ToString for T ### Description Provides a way to convert a value into a `String`. ### Methods - **fn to_string(&self) -> String**: Converts the given value to a `String`. ## impl TryFrom for T ### Description Provides a fallible way to convert a value of type `U` into a value of type `T`. ### Associated Types - **Error = Infallible**: The type returned in the event of a conversion error. ### Methods - **fn try_from(value: U) -> Result>::Error>**: Performs the conversion. ## impl TryInto for T ### Description Provides a fallible way to convert a value of type `T` into a value of type `U`, where `U` implements `TryFrom`. ### Associated Types - **Error = >::Error**: The type returned in the event of a conversion error. ### Methods - **fn try_into(self) -> Result>::Error>**: Performs the conversion. ## impl DeserializeOwned for T ### Description Marker trait for types that can be deserialized into an owned value. ## impl ErasedDestructor for T ### Description Provides a way to erase the destructor of a type, allowing for dynamic dispatch. ``` -------------------------------- ### Implement Any for T Source: https://docs.rs/validator/0.20.0/validator/enum.ValidationErrorsKind.html Provides runtime type information for any type T that implements the 'static trait bound. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### ValidateIp Implementation Source: https://docs.rs/validator/0.20.0/validator/struct.ValidationErrors.html Provides methods to validate IP addresses (IPv4, IPv6, or general IP). ```APIDOC ## GET /validate_ip ### Description Validates if a given string represents an IP address. ### Method GET ### Endpoint /validate_ip ### Query Parameters - **ip_string** (string) - Required - The string to validate as an IP address. ### Response #### Success Response (200) - **is_valid** (boolean) - True if the string is a valid IP address, false otherwise. #### Response Example ```json { "is_valid": true } ``` ## GET /validate_ipv4 ### Description Validates if a given string represents an IPv4 address. ### Method GET ### Endpoint /validate_ipv4 ### Query Parameters - **ip_string** (string) - Required - The string to validate as an IPv4 address. ### Response #### Success Response (200) - **is_valid** (boolean) - True if the string is a valid IPv4 address, false otherwise. #### Response Example ```json { "is_valid": true } ``` ## GET /validate_ipv6 ### Description Validates if a given string represents an IPv6 address. ### Method GET ### Endpoint /validate_ipv6 ### Query Parameters - **ip_string** (string) - Required - The string to validate as an IPv6 address. ### Response #### Success Response (200) - **is_valid** (boolean) - True if the string is a valid IPv6 address, false otherwise. #### Response Example ```json { "is_valid": true } ``` ``` -------------------------------- ### Email User and Domain Regex Definitions Source: https://docs.rs/validator/0.20.0/src/validator/validation/email.rs.html Defines static Regex for validating the user part of an email address and the domain part. The domain regex also handles IP addresses enclosed in brackets. ```rust static EMAIL_USER_RE: Lazy = Lazy::new(|| Regex::new(r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+$").unwrap()); static EMAIL_DOMAIN_RE: Lazy = Lazy::new(|| { Regex::new( r"^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" ).unwrap() }); // literal form, ipv4 or ipv6 address (SMTP 4.1.3) static EMAIL_LITERAL_RE: Lazy = Lazy::new(|| Regex::new(r"^\[([a-fA-F0-9:\.]+)$" ).unwrap()); ``` -------------------------------- ### Data Validation with Validate Derive Source: https://docs.rs/validator/0.20.0/validator/index.html Demonstrates how to use the Validate derive macro on a struct to enforce validation rules on fields. ```APIDOC ## Rust Struct Validation ### Description Use the `#[derive(Validate)]` macro to define validation rules directly on struct fields. The `validate()` method is then called on an instance to check all constraints. ### Request Example ```rust #[derive(Debug, Validate, Deserialize)] struct SignupData { #[validate(email)] mail: String, #[validate(url)] site: String, #[validate(length(min = 1))] first_name: String, #[validate(range(min = 18, max = 20))] age: u32, } ``` ### Response - **Result** (Result<(), ValidationErrors>) - Returns Ok(()) if all validations pass, or a ValidationErrors object containing details of failed constraints. ``` -------------------------------- ### length Method for &str Source: https://docs.rs/validator/0.20.0/validator/trait.ValidateLength.html Implementation of the length method for string slices (&str) to return their length as u64. ```rust fn length(&self) -> Option ``` -------------------------------- ### Available Validations Source: https://docs.rs/validator/0.20.0/src/validator/lib.rs.html A list of all available validation attributes supported by the validator crate. ```APIDOC ## Available Validations ### Description This table lists the validation attributes that can be used with the `validator` crate. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Validation Table: | Validation | Notes | | ----------------------- | ----------------------------------------------------- | | `email` | Validates if the string is a valid email address. | | `url` | Validates if the string is a valid URL. | | `length` | Validates the length of a string or collection. | | `range` | Validates if a number is within a specified range. | | `must_match` | Validates if a string matches a given pattern. | | `contains` | Validates if a string contains a specific substring. | | `does_not_contain` | Validates if a string does not contain a specific substring. | | `custom` | Allows for custom validation logic via a function. | | `regex` | Validates if a string matches a regular expression. | | `credit_card` | (Requires the feature `card` to be enabled) | | `non_control_character` | (Required the feature `unic` to be enabled) | | `required` | Validates that a field is not empty or null. | ``` -------------------------------- ### Implement StructuralPartialEq for ValidationErrorsKind Source: https://docs.rs/validator/0.20.0/validator/enum.ValidationErrorsKind.html Provides structural equality comparison for ValidationErrorsKind, which may differ from standard equality in certain complex scenarios. -------------------------------- ### Implement TryInto for T Source: https://docs.rs/validator/0.20.0/validator/enum.ValidationErrorsKind.html Enables a fallible conversion from type T into type U. This is the reciprocal of TryFrom. ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Test URL Validation with Cow<'_, str> Source: https://docs.rs/validator/0.20.0/src/validator/validation/urls.rs.html Tests the `validate_url` method with `Cow<'static, str>` instances created from both string literals and `String` objects. It verifies that both owned and borrowed `Cow` variants are correctly validated. ```rust use std::borrow::Cow; use super::ValidateUrl; #[test] fn test_validate_url_cow() { let test: Cow<'static, str> = "http://localhost:80".into(); assert!(test.validate_url()); let test: Cow<'static, str> = String::from("http://localhost:80").into(); assert!(test.validate_url()); let test: Cow<'static, str> = "http".into(); assert!(!test.validate_url()); let test: Cow<'static, str> = String::from("http").into(); assert!(!test.validate_url()); } ``` -------------------------------- ### Available Validations Source: https://docs.rs/validator/0.20.0/validator A list of built-in validation types supported by the `validator` crate, along with notes on their usage and any feature flag requirements. ```APIDOC ## Available Validations This section lists the various validation types supported by the `validator` crate. | Validation | Notes | |---|---| | `email` | Validates if the string is a valid email address according to the HTML5 specification. | | `url` | Validates if the string is a valid URL. | | `length` | Validates the length of a string or collection. Can specify `min`, `max`, or `equal`. | | `range` | Validates if a numeric value falls within a specified range. Supports `min`, `max`, `exclusive_min`, and `exclusive_max`. | | `must_match` | Validates that two fields match each other. | | `contains` | Validates if a string contains a specific substring. | | `does_not_contain` | Validates if a string does not contain a specific substring. | | `custom` | Allows for custom validation logic defined in a separate function. | | `regex` | Validates if a string matches a given regular expression. | | `credit_card` | Validates if a string is a valid credit card number. Requires the `card` feature to be enabled. | | `non_control_character` | Validates that a string does not contain control characters. Requires the `unic` feature to be enabled. | | `required` | Validates that an `Option` field is not `None`. | For more in-depth usage descriptions and examples, please refer to the project's README file. ``` -------------------------------- ### Implement Serialize for ValidationErrorsKind Source: https://docs.rs/validator/0.20.0/validator/enum.ValidationErrorsKind.html Allows ValidationErrorsKind to be serialized into various formats using Serde. This is useful for sending validation results over networks or storing them. ```rust fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where __S: Serializer, ``` -------------------------------- ### Implement ValidateUrl for Cow<'_, str> Source: https://docs.rs/validator/0.20.0/src/validator/validation/urls.rs.html Implements the `ValidateUrl` trait for `Cow<'_, str>`. It delegates the `as_url_string` call to the underlying `str` implementation, allowing `Cow` to be validated as a URL. ```rust impl ValidateUrl for Cow<'_, str> { fn as_url_string(&self) -> Option> { ::as_url_string(self) } } ``` -------------------------------- ### Implement ValidateUrl for Option Source: https://docs.rs/validator/0.20.0/src/validator/validation/urls.rs.html Implements the `ValidateUrl` trait for `Option` where `T` also implements `ValidateUrl`. If the Option is `None`, it returns `None` for `as_url_string`, otherwise it forwards the call to the inner `T`. ```rust impl ValidateUrl for Option where T: ValidateUrl, { fn as_url_string(&self) -> Option> { let Some(u) = self else { return None; }; T::as_url_string(u) } } ``` -------------------------------- ### Implement TryFrom for T Source: https://docs.rs/validator/0.20.0/validator/enum.ValidationErrorsKind.html Provides a fallible conversion from type U into type T. This is useful when the conversion might fail. ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### Implement Into for T Source: https://docs.rs/validator/0.20.0/validator/enum.ValidationErrorsKind.html Enables conversion from type T into type U, provided that U implements From. This is a convenient way to perform type conversions. ```rust fn into(self) -> U ``` -------------------------------- ### Implement PartialEq for ValidationErrorsKind Source: https://docs.rs/validator/0.20.0/validator/enum.ValidationErrorsKind.html Defines equality comparison for ValidationErrorsKind. Use this to check if two error instances represent the same validation failure. ```rust fn eq(&self, other: &ValidationErrorsKind) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Test IPv6 Address Validation Source: https://docs.rs/validator/0.20.0/src/validator/validation/ip.rs.html Tests the `validate_ipv6` method with various valid and invalid IPv6 address strings, including compressed and mixed notations. Also demonstrates usage with `Cow<'static, str>`. ```rust use super::ValidateIp; use std::borrow::Cow; #[test] fn test_validate_ip_v6() { let tests = vec![ ("fe80::223:6cff:fe8a:2e8a", true), ("2a02::223:6cff:fe8a:2e8a", true), ("1::2:3:4:5:6:7", true), ("::", true), ("::a", true), ("2::", true), ("::ffff:254.42.16.14", true), ("::ffff:0a0a:0a0a", true), ("::254.42.16.14", true), ("::0a0a:0a0a", true), ("foo", false), ("127.0.0.1", false), ("12345::", false), ("1::2::3::4", false), ("1::zzz", false), ("1:2", false), ("fe80::223: 6cff:fe8a:2e8a", false), ("2a02::223:6cff :fe8a:2e8a", false), ("::ffff:999.42.16.14", false), ("::ffff:zzzz:0a0a", false), ]; for (input, expected) in tests { assert_eq!(input.validate_ipv6(), expected); } } #[test] fn test_validate_ip_v6_cow() { let test: Cow<'static, str> = "fe80::223:6cff:fe8a:2e8a".into(); assert!(test.validate_ipv6()); let test: Cow<'static, str> = String::from("fe80::223:6cff:fe8a:2e8a").into(); assert!(test.validate_ipv6()); let test: Cow<'static, str> = "::ffff:zzzz:0a0a".into(); assert!(!test.validate_ipv6()); let test: Cow<'static, str> = String::from("::ffff:zzzz:0a0a").into(); assert!(!test.validate_ipv6()); } ``` -------------------------------- ### Email Validation Test Cases Source: https://docs.rs/validator/0.20.0/src/validator/validation/email.rs.html A comprehensive list of test cases for email validation, including valid and invalid formats. This is used to test the `validate_email` function. ```rust ("a@atm.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", true), ("a@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.atm", true), ( "a@aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbb.atm", true, ), // 64 * a ("a@atm.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false), ("", false), ("abc", false), ("abc@", false), ("abc@bar", true), ("a @x.cz", false), ("abc@.com", false), ("something@@somewhere.com", false), ("email@127.0.0.1", true), ("email@[127.0.0.256]", false), ("email@[2001:db8::12345]", false), ("email@[2001:db8:0:0:0:0:1]", false), ("email@[::ffff:127.0.0.256]", false), ("example@invalid-.com", false), ("example@-invalid.com", false), ("example@invalid.com-", false), ("example@inv-.alid-.com", false), ("example@inv-.-alid.com", false), (r#"test@example.com\n\n