RodValidate

Derive Macro RodValidate 

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

Derives the RodValidate trait for a struct.

Implements validation logic for struct fields annotated with #[rod(...)]. Fields without the attribute are required to implement RodValidate. Many standard types are supported, including [RodStringContent][crate::types::RodStringContent], [RodIntegerContent][crate::types::RodIntegerContent], [RodLiteralContent][crate::types::RodLiteralContent], [RodBooleanContent][crate::types::RodBooleanContent], and [RodOptionContent][crate::types::RodOptionContent]. To see the available attributes, refer to the documentation for each type.

§Examples

use rod::prelude::*;

#[derive(RodValidate)]
struct User {
    #[rod(
        String {
            length: 3..=12, // Length between 3 and 12 characters
        }
    )]
    username: String,
    #[rod(
        u8 {
            size: 18..=99, // Age between 18 and 99
        }
    )]
    age: u8,
}

§Invalid Examples

This example demonstrates a struct that does not implement RodValidate.

use rod::prelude::*;

struct DoesNotImplementRodValidate {
    field: String,
}

#[derive(RodValidate)] // This will fail to compile
struct Test {
    #[rod(
        String {
            length: 5..=10,
        }
    )]
    field1: String,
    field2: DoesNotImplementRodValidate, // This field does not implement RodValidate
}

§Custom Validations

You can also define custom validations using the check attribute. Use a closure to define the validation logic. The closure should take a single argument, which is the field value, and return a boolean indicating whether the validation passed or failed.

use rod::prelude::*;
#[derive(RodValidate)]
struct MyEntity {
   #[rod(
       String {
           length: 5..=10,
       },
       check = |s| {
          s.chars().all(|c| c.is_alphanumeric())
       }
    )]
    my_string: String,
}
let entity = MyEntity {
    my_string: "Hello123".to_string(),
};
assert!(entity.validate().is_ok());