validatable 0.1.0

Define validated data types once and share them between the frontend and backend of isomorphic Rust web applications, with plain, input, and form representations
Documentation

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 validatable::*;

// A reusable validated string type: trimmed, then 1..=20 characters.
type UserName = Validated<String, Chain<Trim, LengthRange<1, 20>>>;

#[derive(Validatable, PartialEq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct User<F: FieldFamily> {
    name: Field<F, UserName>,
    age: Field<F, u8>,
    active: Field<F, bool>,
}

// Frontend: the user edits a `User<Form>`.
let mut form = User::<Form>::default();
form.name.input("  Alice  ".to_string());
form.age.input("17".to_string());
form.active.input(true);

// Validation yields a `User<Plain>` on success.
let user: User<Plain> = form.validate().expect("form is valid");
assert_eq!(user.name.to_string(), "Alice"); // trimmed by `Trim`
assert_eq!(user.age, 17);

// On failure it returns `None` and writes a message into each offending field.
form.age.input("seventeen".to_string());
assert_eq!(form.validate(), None);
assert_eq!(
    form.age.message,
    Some(Message::BadFormat(Format::UnsignedInteger))
);

// UI-less input (e.g. an API request payload) uses `User<Input>`.
let input = User::<Input> {
    name: "Bob".to_string(),
    age: "42".to_string(),
    active: true,
};
let user: User<Plain> = input.validate().expect("input is valid");

// `User<Plain>` serializes as ordinary data for storage or transfer,
// with the `serde` feature enabled.
#[cfg(feature = "serde")]
{
    let json = serde_json::to_string(&user).unwrap();
    assert_eq!(json, r#"{"name":"Bob","age":42,"active":true}"#);
}

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> or T<Input> into a T<Plain> and work safely with that,
    • serialize T<Plain> data into storage,
    • restore T<Plain> data from trusted storage.
  • 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.

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.
fn create_user(input: User<Input>) -> Result<User<Plain>, User<Form>> {
    let mut form = input.into_form();
    match form.validate() {
        Some(user) => Ok(user),
        None => Err(form),
    }
}

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 = Validated<String, Chain<Trim, LengthRange<1, 20>>>;
type Quantity = Validated<u32, Trim, UnsignedValueRange<5, 100>>;
type Rating   = Validated<f64, True, FloatValueRangeX1000<0, 5_000>>; // 0.0..=5.0
type Hex      = Validated<NonEmptyString, AllChars<CharClassAsciiHexdigit>>;

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 with And / Or / Not); an empty string passes vacuously — use NonEmptyString as the plain type or add LengthMin<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 = Validated<NonEmptyString, Chain<AllChars<CharClassAscii>, Variant<1>>>;
    type Id   = Validated<NonEmptyString, Chain<AllChars<CharClassAscii>, Variant<2>>>;
    // 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 validatable::*;

type Name = Validated<String, Chain<Trim, LengthRange<1, 40>>>;
type Zip = Validated<String, Chain<AllChars<CharClassAsciiDigit>, LengthRange<7, 7>>>;
type Quantity = Validated<u32, Trim, UnsignedValueRange<1, 99>>;

#[derive(Validatable, PartialEq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct Address<F: FieldFamily> {
    city: Field<F, Name>,
    zip: Field<F, Zip>,
}

#[derive(Validatable, PartialEq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct OrderLine<F: FieldFamily> {
    product: Field<F, Name>,
    quantity: Field<F, Quantity>,
}

#[derive(Validatable, PartialEq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct Order<F: FieldFamily> {
    shipping: Address<F>,     // nested: an `Address<Form>` inside an `Order<Form>`
    lines: Vec<OrderLine<F>>, // repeated rows: `Vec<OrderLine<Form>>`
}

let mut form = Order::<Form>::default(); // `lines` starts empty
form.shipping.city.input("Osaka".to_string());
form.shipping.zip.input("5300001".to_string());

// The user clicks "add line": push a fresh sub-form and edit it.
form.lines.push(OrderLine::<Form>::default());
form.lines[0].product.input("Coffee beans".to_string());
form.lines[0].quantity.input("2".to_string());
form.lines.push(OrderLine::<Form>::default());
form.lines[1].product.input("Paper filter".to_string());
form.lines[1].quantity.input("0".to_string());

// Validation walks the whole tree; the error lands on the exact field.
assert_eq!(form.validate(), None);
assert_eq!(
    form.lines[1].quantity.message,
    Some(Message::ValueExceedMin("1".to_string()))
);

form.lines[1].quantity.input("3".to_string());
let order: Order<Plain> = form.validate().expect("form is valid");

// The validated tree serializes as ordinary nested data,
// with the `serde` feature enabled.
#[cfg(feature = "serde")]
{
    let json = serde_json::to_string(&order).unwrap();
    assert_eq!(
        json,
        r#"{"shipping":{"city":"Osaka","zip":"5300001"},"lines":[{"product":"Coffee beans","quantity":2},{"product":"Paper filter","quantity":3}]}"#
    );
}

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 as Field<F, T>, FieldWith<F, Plain, Form, Input>, or a nested derived type Inner<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 routes validate() through your CustomValidate impl on T<Form>, for cross-field rules (implemented with validate_by, which first runs the derived per-field validation). The rule only holds for values that actually went through validate(): T<Plain> is a struct, so if its fields are pub, 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 by T<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/implements Serialize and Deserialize for 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

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.