Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Getting Started

Install

Add Fortifier to your project:

cargo add fortifier --features email-address

See Installation for more details.

Data structure

Define a data structure:

#![allow(unused)]
fn main() {
struct CreateUser {
    email_address: String,
    name: String,
}
}

Derive

Derive the Validate trait:

#![allow(unused)]
fn main() {
extern crate fortifier;
use fortifier::Validate;

#[derive(Validate)]
struct CreateUser {
    email_address: String,
    name: String,
}
}

Validations

Define validations:

#![allow(unused)]
fn main() {
extern crate fortifier;
use fortifier::Validate;

#[derive(Validate)]
struct CreateUser {
    #[validate(email_address)]
    email_address: String,

    #[validate(length(min = 1, max = 256))]
    name: String,
}
}

Validate

Fortifier supports both synchronous and asynchronous validation. This example will only use synchronous validation.

Call the validate_sync method on the data structure:

extern crate fortifier;

use fortifier::{
    EmailAddressError,
    EmailAddressErrorCode,
    LengthError,
    LengthErrorCode,
    Validate,
    ValidationErrors,
};

#[derive(Validate)]
struct CreateUser {
    #[validate(email_address)]
    email_address: String,

    #[validate(length(min = 1, max = 256))]
    name: String,
}

fn main() {
    let data = CreateUser {
        email_address: "amy.pond@example.com".to_string(),
        name: "Amy Pond".to_string(),
    };

    assert_eq!(data.validate_sync(), Ok(()));

    let data = CreateUser {
        email_address: "invalid".to_string(),
        name: "".to_string(),
    };

    assert_eq!(
        data.validate_sync(),
        Err(ValidationErrors::from_iter([
            CreateUserValidationError::EmailAddress(
                EmailAddressError::MissingSeparator {
                    code: EmailAddressErrorCode,
                },
            ),
            CreateUserValidationError::Name(
                LengthError::Min {
                    code: LengthErrorCode,
                    min: 1,
                    value: 0,
                }
            ),
        ])),
    );
}

Next Steps

  • Installation - Lists all available features.
  • Validate - Describes how to use the Validate derive macro.
  • Validations - Explains all available validations and their options.