1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! 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 use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use Validatable;