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
//! 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 [`FieldFamily`] 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>,
//! }
//! #
//! # fn main() {
//!
//! // 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<F, P>`](Field) resolves through `P`'s
//! [`DefaultInputType`]):
//!
//! | 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>`** is the validated value, plain and simple. The backend
//! validates a submitted `T<Form>` or `T<Input>` into a `T<Plain>` and works
//! with that, serializes `T<Plain>` data into storage, and restores it from
//! trusted storage; the frontend receives `T<Plain>` data from the backend
//! for display (detail and list views, and as the starting point for an
//! edit form via [`into_form`](Validatable::into_form)).
//!
//! **`T<Form>`** represents an input form editing a `T`. Every field holds
//! the input in an editable representation — a numeric field is a `String`
//! the user can type digits into — together with the latest validation
//! result (see [`Edit`]). Calling
//! [`validate`](ValidatableForm::validate) checks all fields, stores a
//! [`Message`] on each invalid one, and returns the `T<Plain>` when
//! everything is valid.
//!
//! **`T<Input>`** is `T<Form>` stripped of the validation results: input
//! without a UI, such as an API request body. A typical endpoint receives a
//! `T<Input>` and responds with `Result<T<Plain>, T<Form>>`, so the client
//! learns exactly which fields failed:
//!
//! ```
//! # use validatable::*;
//! # 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>,
//! # }
//! # fn main() {
//! // 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),
//!     }
//! }
//!
//! let bad = User::<Input> {
//!     name: "  ".to_string(),
//!     age: "x".to_string(),
//!     active: false,
//! };
//! let form = create_user(bad).unwrap_err();
//! assert_eq!(form.name.message, Some(Message::Empty));
//! assert_eq!(
//!     form.age.message,
//!     Some(Message::BadFormat(Format::UnsignedInteger))
//! );
//! # }
//! ```
//!
//! # Building blocks
//!
//! * [`Validated`] wraps a value with type-level [`Validator`]s
//!   ([`Trim`], [`LengthRange`], [`UnsignedValueRange`], [`AllChars`], …),
//!   composed with [`Chain`], [`And`], [`Or`], and [`Not`].
//! * Custom field types implement [`ValidatableValue`]; custom rules
//!   implement [`Validator`]; cross-field validation uses
//!   [`CustomValidate`] / [`Validatable::validate_by`].
//! * Collections: `Vec<T>`, [`NonEmpty<T>`], and [`BoundedVec<T, MIN, MAX>`]
//!   of validatable elements are validatable themselves.
//! * Nesting: a derived type can be used as a field of another derived type
//!   (`Field<F, …>` or `Inner<F>` directly).
//!
//! # Nesting 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>>`
//! }
//! #
//! # fn main() {
//!
//! 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).
//!
//! # 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. See [`ValidatedValue`] for details.
//!
//! # 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.

pub mod boundedvec;
pub mod family;
pub mod implementations;
pub mod types;
pub mod validated;
pub mod validator;

pub use self::boundedvec::*;
pub use self::family::*;
pub use self::implementations::*;
pub use self::types::*;
pub use self::validated::*;
pub use self::validator::*;
pub use validatable_derive::Validatable;