validatable
Define a data type once and share it — with validation — between the frontend and backend of an isomorphic Rust web application.
A type deriving Validatable is generic over a field family and expands
into three synchronized representations:
T<Plain>— the validated domain value.T<Input>— the raw input, e.g. an API request payload.T<Form>— the form state while editing, with a validation result per field.
The only ways to obtain a T<Plain> are validating a T<Form> or
T<Input>, or deserializing from trusted storage — so "this data has been
validated" becomes a guarantee of the type system, for invariants that live
entirely inside one field. A Validated field is safe to make pub: its
only constructor is validation, so a struct literal can only place an
already-valid value there. But T<Plain> itself is a struct, and a struct
literal is a constructor too — if its fields are pub (a common pattern
when building API payloads), any invariant that spans more than one field
can be violated by assembling independently valid field values into a
combination that was never actually validated together, regardless of
whether CustomValidate / #[validatable(custom_validate)] checks that
combination during a real validate() call. Keep the fields of a type with
cross-field invariants private — and expose read accessors instead —
whenever those invariants must hold unconditionally.
Example
use *;
// A reusable validated string type: trimmed, then 1..=20 characters.
type UserName = ;
// Frontend: the user edits a `User<Form>`.
let mut form = default;
form.name.input;
form.age.input;
form.active.input;
// Validation yields a `User<Plain>` on success.
let user: = form.validate.expect;
assert_eq!; // trimmed by `Trim`
assert_eq!;
// On failure it returns `None` and writes a message into each offending field.
form.age.input;
assert_eq!;
assert_eq!;
// UI-less input (e.g. an API request payload) uses `User<Input>`.
let input = ;
let user: = input.validate.expect;
// `User<Plain>` serializes as ordinary data for storage or transfer,
// with the `serde` feature enabled.
The single definition of User above produces these three concrete types:
| field | User<Plain> |
User<Input> |
User<Form> |
|---|---|---|---|
name |
UserName |
String |
Edit<String> |
age |
u8 |
String |
Edit<String> |
active |
bool |
bool |
Edit<bool> |
The three representations
T<Plain>
The validated value, plain and simple.
- On the backend:
- validate a submitted
T<Form>orT<Input>into aT<Plain>and work safely with that, - serialize
T<Plain>data into storage, - restore
T<Plain>data from trusted storage.
- validate a submitted
- On the frontend:
- receive
T<Plain>data from the backend (detail and list views), and turn it into a form with.into_form()when editing starts.
- receive
T<Form>
The state of an input form while the user edits a T. Each field holds its
input in an editable representation — a numeric field is a String the user
can type into — together with the latest validation result (Edit<I> with
value, message, and edited). form.validate() checks every field,
stores a Message on each invalid one, and returns the T<Plain> when the
whole form is valid. The edited flag is set by Edit::input and lets the
UI suppress error messages on fields the user has not touched yet.
T<Input>
T<Form> stripped of the validation results: input without a UI, mainly for
sending data to the backend through an API. A typical endpoint receives a
T<Input> and responds with Result<T<Plain>, T<Form>>, so the client
learns exactly which fields failed:
// Backend endpoint: validate the payload, return per-field errors on failure.
Validated primitive values
Validated<T, VI, VP> attaches type-level validators to a single value:
VI validates (and may transform) the raw input before parsing, VP
validates the parsed value. Validators are zero-sized types composed with
Chain / And / Or / Not:
type UserName = ;
type Quantity = ;
type Rating = ; // 0.0..=5.0
type Hex = ;
NonEmptyString (re-exported from
non-empty-string) can serve as
the plain type when the value must not be empty: the input is validated as a
String and non-emptiness is enforced when it is parsed, so empty input
fails with Message::Empty even when the validators accept it.
Built-in validators include:
-
LengthMin/LengthMax/LengthRange— string length in characters (chars().count(), not bytes) -
SignedValueMin/Max/Range,UnsignedValueMin/Max/Range— integer bounds -
FloatValueMinX1000/MaxX1000/RangeX1000— float bounds given as integers scaled by 1000 (const generics cannot be floats); beware of values not exactly representable in the target float type -
AllChars<C>— all characters must belong to a character class (CharClassAsciiDigit,CharClassAlphanumeric,CharClassJust<'x'>, …, composable withAnd/Or/Not); an empty string passes vacuously — useNonEmptyStringas the plain type or addLengthMin<1>when content is required -
Trim,TrimChars<C>,RemoveChars<C>— transforming validators that change the value (the validated result may differ from the input) -
Variant<N>— a no-op marker that makes otherwise identical types distinct:type Name = ; type Id = ; // Name and Id validate identically but cannot be mixed up.
Custom rules implement the Validator trait; custom field types implement
ValidatableValue.
Nested types and collections
Derived types nest: a Validatable type — or a Vec of one — is a field
like any other, and every representation nests accordingly. The form of the
Order below contains an Address<Form> and one OrderLine<Form> per row,
so an "add line" button in the UI just pushes a default sub-form:
use *;
type Name = ;
type Zip = ;
type Quantity = ;
let mut form = default; // `lines` starts empty
form.shipping.city.input;
form.shipping.zip.input;
// The user clicks "add line": push a fresh sub-form and edit it.
form.lines.push;
form.lines.product.input;
form.lines.quantity.input;
form.lines.push;
form.lines.product.input;
form.lines.quantity.input;
// Validation walks the whole tree; the error lands on the exact field.
assert_eq!;
assert_eq!;
form.lines.quantity.input;
let order: = form.validate.expect;
// The validated tree serializes as ordinary nested data,
// with the `serde` feature enabled.
Swap Vec for NonEmpty or BoundedVec when the number of rows must be
constrained (e.g. an order needs at least one line).
Derive reference
#[derive(Validatable)] supports two kinds of types:
- Family mode — a struct or enum with exactly one generic parameter
bound by
FieldFamily. Fields written asField<F, T>,FieldWith<F, Plain, Form, Input>, or a nested derived typeInner<F>switch representation per family; all other fields stay the same in all three representations. For enums, the default input is the first variant. - Newtype mode — a single-field tuple struct such as
struct UserId(Validated<u64, Trim>);, which forwards validation to the inner type so the newtype can be used as a field.
Attributes:
#[validatable(custom_validate)]on the type routesvalidate()through yourCustomValidateimpl onT<Form>, for cross-field rules (implemented withvalidate_by, which first runs the derived per-field validation). The rule only holds for values that actually went throughvalidate():T<Plain>is a struct, so if its fields arepub, a struct literal is just another constructor, and it can assemble a combination of independently valid field values that this rule never checked. Keep the fields private when the invariant must hold unconditionally.#[validatable(default = expr)]on a field overrides the default input value used byT<Form>::default()/T<Input>::default().
Do not also write #[derive(Default)] on a type deriving Validatable:
the derive already implements Default for T<Form> and T<Input>, and a
second, derived Default impl for the same generic type conflicts with it
(E0119).
Collections compose: Vec<T>, NonEmpty<T> (re-exported from
nonempty), and
BoundedVec<T, MIN, MAX> (length checked at validation time, MIN <= MAX
checked at compile time) of validatable elements are validatable themselves.
Deserialization is not validation
Deserialize implementations in this crate restore data without running
any validators. Deserialization is a conversion intended for trusted
sources — your own storage, your own backend. Data from untrusted sources
must be received as T<Input> / T<Form> and validated explicitly. Note
that a plain type's own Deserialize implementation still applies its own
constraints: deserializing an empty string into a
Validated<NonEmptyString, …> fails, for example, because NonEmptyString
itself rejects it.
Requirements
Field types are currently expected to satisfy
PartialEq + Clone + Debug, plus Serialize + DeserializeOwned when the
serde feature is enabled — see FieldBounds.
Feature flags
serde(off by default) — derives/implementsSerializeandDeserializefor the crate's own types (Edit,Message,Format,BoundedVec,ValidatedValue, the family markers) and requires field types to implement them too.
License
Licensed under either of
- Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (http://opensource.org/licenses/MIT)
at your option. See LICENSE for the full text of both licenses.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.