Skip to main content

Module validation

Module validation 

Source
Expand description

Form validation with Laravel-style rules, database-backed unique and exists, and English messages (an app translates them in its lang files).

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct ProductForm {
    name: String,
    price: i64,
    email: Option<String>,
}

impl Validate for ProductForm {
    fn rules(&self, v: &mut Validator) {
        v.field("name", &self.name).required().max(100).unique("products", "name");
        v.field("price", &self.price).label("sale price").min(1_000);
        v.field("email", &self.email).email();
    }
}

async fn store(State(db): State<Db>, back: Back, Valid(form): Valid<ProductForm>) -> Result<Back> {
    // `form` passed every rule; invalid input never gets here.
    Ok(back)
}

Structs§

Dimensions
Limits for an uploaded image’s size in pixels, for Field::dimensions (Laravel’s dimensions).
Errors
Validation errors: messages keyed by field name.
Field
The rules for one field, chained: v.field("name", &self.name).required().max(100).
FormContext
What Validate::authorize and Validate::after see of the request.
KeyValues
Pairs of text in the order they were entered, like headers or settings: what the UI kit’s key_value field sends (meta[0][key], meta[0][value], …). Rows without a key are skipped, and a key entered twice keeps its last value.
Password
What a password must contain; Field::password(&policy) checks it. The built-in register, reset and account forms use the app’s policy (Auth::password_rules), Password::min(8) by default.
Valid
Deserializes and validates a form (urlencoded or multipart with Upload fields), a JSON body, or the query string for GET, with the type’s Validate rules.
ValidationError
A failed validation. As a response it is 422 with {"message": ..., "errors": {...}}; for regular (non-HTMX, non-JSON) requests Renox turns it into a redirect back with the errors and old input flashed to the session.
Validator
Collects rule failures. Rules run in order and stop at a field’s first failure; rules other than required and accepted skip empty values.

Enums§

Inspected
What a rule sees of a field’s value.

Traits§

FieldValue
A value that can be validated. Implemented for strings, numbers, bool, Option<T> and Vec<T>.
Rule
A rule to reuse across forms, e.g. a tax number:
Validate
Declares the rules for a form. Used by the Valid<T> extractor, which calls, in order: prepare, authorize, rules and, when they pass, after. Only rules is required.
ValidateHooks
prepare, authorize and after for a struct with #[derive(Validate)], which writes rules from its #[validate(…)] attributes: add #[validate(hooks)] on the struct and implement the ones you need.