Smeltery
Get started

The basics

v0.1

Validation

#[derive(Validate)] puts rules on a form struct, and the Valid<T> extractor reads, checks and hands it over:

rust
use serde::Deserialize;
use smeltery::prelude::*;

#[derive(Deserialize, Validate)]
pub struct RegisterForm {
    #[validate(required, max = 255)]
    pub name: String,
    #[validate(required, email, unique(table = "users", column = "email"))]
    pub email: String,
    #[validate(required, min = 8, confirmed)]
    pub password: String,
    pub password_confirmation: String,
    #[validate(integer, between(1, 120))]
    pub age: Option<i64>,
}

async fn store(session: Session, Valid(form): Valid<RegisterForm>) -> Redirect {
    session.flash("status", format!("Welcome, {}!", form.name));
    Redirect::to("/")
}
Rule Passes when Message
required present and not blank The name field is required.
email an e-mail address The email field must be a valid email address.
url an http/https URL The site field must be a valid URL.
min = n, max = n, between(a, b) text: characters; numbers: the value; lists: items; uploaded files: kilobytes The password field must be at least 8 characters. / The name field must not be greater than 255 characters.
mimes = "png,jpg" an uploaded file whose name has one of the extensions The image field must be a file of type: png, jpg.
numeric, integer a number / a whole number The age field must be an integer.
alpha, alpha_num, alpha_dash letters / letters and digits / also - and _ The code field must only contain letters.
in_list("a", "b") one of the values The selected color is invalid.
confirmed equals <field>_confirmation The password field confirmation does not match.
same = "other" equals field other The email field must match other.
accepted yes, on, 1, true The terms field must be accepted.
unique(table = "users", column = "email") no row has the value The email has already been taken.
exists(table = "users", column = "id") a row has the value The selected manager id is invalid.

message = "…" replaces the messages of that field. unique(…, except_id) ignores the row whose id is the route's last path parameter (an edit form); except_id = "field" takes the id from a field of the struct. unique and exists query the app's database. In messages, _ in a field name becomes a space.

Valid<T> reads a URL-encoded or multipart form, or JSON when the request's content type is JSON. Fields holding an empty string are dropped before deserializing, so an empty input is absent: an Option field is None, and every rule except required skips an absent field. When the input does not deserialize at all, the messages of the required, email, url, numeric and integer rules are reported for every field at once.

File uploads. A form with enctype="multipart/form-data" reaches the same Valid<T>. A file field is an Option<UploadedFile> (smeltery::http::UploadedFile); text fields deserialize as in a URL-encoded form:

rust
use serde::Deserialize;
use smeltery::http::UploadedFile;
use smeltery::prelude::*;

#[derive(Deserialize, Validate)]
pub struct PhotoForm {
    #[validate(required, max = 255)]
    pub title: String,
    #[validate(required, max = 2048, mimes = "png,jpg")]
    pub image: Option<UploadedFile>,
}

async fn store(Valid(form): Valid<PhotoForm>) -> Result<Redirect> {
    if let Some(image) = &form.image {
        let path = image.store("public/photos").await?; // "public/photos/<random>.png"
    }
    Ok(Redirect::to("/photos"))
}

On a file, required passes when a file was sent (a file input left empty is absent), min, max and between count kilobytes, and mimes = "png,jpg" checks the file name's extension (jpg and jpeg are one). Each file streams to a temp file in storage/framework/uploads/, which is deleted when the UploadedFile is dropped unless it was stored. Before any rule runs, the first bytes are checked against the declared type and the extension: PNG, JPEG, GIF, WebP and PDF content must be declared and named as that type, and a file declared or named as one of them must contain it; otherwise the field fails with "The image field must be a file whose content matches its type.". A multipart request may be UPLOAD_MAX_BYTES (default 10 MB) in all; a larger one fails validation on the field being read ("must not be greater than … kilobytes"), and its text fields together stay within BODY_LIMIT (413 past it). The whole body, boundaries and part headers included, may be at most 1 MB more than UPLOAD_MAX_BYTES, and hold at most 1000 parts (413 past either). name() is the browser's file name without directories and with unsafe characters replaced, size() is in bytes, mime() is the type read from the content (else the declared one), and bytes() reads the file. store(dir) moves it to storage/app/<dir>/<40 random characters>.<extension> and returns that path relative to storage/app. The extension follows the content for PNG, JPEG, GIF, WebP and PDF files (a photo.exe holding a PNG is stored as .png), else it is the name's own when that is on the list of safe extensions, in lower case: images (png, jpg, jpeg, gif, webp, avif, bmp, ico, tif, tiff, heic, heif …, not svg), audio (mp3, wav, ogg, m4a, flac …), video (mp4, webm, mov …), pdf, txt, csv, tsv, rtf, office documents (docx, xlsx, pptx, odt …) and archives (zip, gz, 7z …). Every other extension (html, svg, xml, xsd, js, an unknown one) is stored as .bin. smeltery::http::is_safe_extension(ext) tells whether an extension is on the list and stored_extension(ext) gives the one store uses. mimes checks the name only, so an image field lists its types in mimes, and the content check above covers those five types. store_as(dir, name) picks the name itself. dir starts with public (served at /storage/… after smeltery storage:link) or private, and every segment of dir and the name uses only [A-Za-z0-9._-] (no ., .. or leading dot in the name). A file field in a URL-encoded or JSON body is invalid. Failed validation flashes the text fields as old input, never the files.

When validation fails, JSON clients (an Accept or Content-Type of JSON) get 422 {"message": "The given data was invalid.", "errors": {"email": ["…"]}}. On web routes other requests are redirected back (303 to the Referer when it is on this site, else /) with the errors and the input flashed; fields that look like secrets are not flashed: names holding password, passwd, passphrase, passcode, secret, token, apikey, privatekey, accesskey, cardnumber, creditcard, securitycode, twofactor or recoverycode once everything but letters and digits is left out (private_key, privateKey and private-key all count), names with one of the words key, pin, otp, totp, mfa, 2fa, tfa, auth, card, cvv, cvc, cvv2, iban, ssn, answer or recovery (words split at anything but letters and digits and at camelCase, so mfaCode and security_answer count; letter case ignored), and the fields named with AppBuilder::dont_flash(&["nickname"]). A value over 16 KB is not flashed, nor more than 100 fields or 64 KB in all. The next page shows them with @error("email") {{ message }} @enderror and old("email"). A handler can fail the same way with Err(Error::validation("email", "…")).

ValidationErrors maps fields to messages: first(field), get(field), has(field), is_empty(), and it serializes as {"field": ["message"]}.

↑↓ moveEnter openEsc close