reinhardt-forms
Django-inspired form handling and validation for Rust
Overview
reinhardt-forms provides a comprehensive form system for form handling and
validation. Inspired by Django's forms framework, it offers generated
model-backed forms and manual form definitions with extensive validation
capabilities.
Target-neutral model schemas and payloads can be shared with WASM code. Native
candidate construction and persistence use the caller's asynchronous ORM
executor. For HTML rendering and WASM form submission, see reinhardt-pages.
Installation
Add reinhardt to your Cargo.toml:
[]
= { = "0.4.0-alpha.6", = ["forms"] }
# Or use a preset:
# reinhardt = { version = "0.4.0-alpha.6", features = ["standard"] } # Recommended
# reinhardt = { version = "0.4.0-alpha.6", features = ["full"] } # All features
# Forms is included in the standard preset
Then import form features:
use ;
Note: Form features are included in the standard and full feature presets.
Features Status
Core Form System
Implemented ✓
-
Form Base (
Form): Complete form data structure with binding and validation- Form creation with initial data and field prefix support
- Data binding and validation lifecycle
- Custom clean functions for form-level and field-level validation
- Field access and manipulation (add, remove, get)
- Initial data and change detection
- Error handling and reporting
- Client-side validation rules (for WASM integration)
-
BoundField: Field bound to form data
- Field data and error binding
- Label and help text support
-
WASM Compatibility (
wasm_compat): WASM-compatible form metadataFormMetadata: Serializable form state for client-side processingFieldMetadata: Field information for client-side renderingValidationRule: Client-side validation rule definitions
Field Types
Implemented ✓
Basic Fields:
CharField: Text input with min/max length, stripping, null character validationIntegerField: Integer input with min/max value constraints, string parsingBooleanField: Boolean/checkbox input with flexible type coercionEmailField: Email validation with regex, length constraints
Advanced Fields:
FloatField: Floating-point number validation with min/max constraintsDecimalField: Precise decimal number handling with scale and precisionDateField: Date input with multiple format support and locale handlingTimeField: Time input with format parsingDateTimeField: Combined date and time validationURLField: URL validation with scheme and max length checksJSONField: JSON data validation and parsingFileField: File upload handling with size validationImageField: Image file validation with dimension checksChoiceField: Selection from predefined choicesMultipleChoiceField: Multiple selection supportRegexField: Pattern-based validation with custom regexSlugField: URL slug validationGenericIPAddressField: IPv4/IPv6 address validationUUIDField: UUID format validationDurationField: Time duration parsingComboField: Multiple field validation combinationMultiValueField: Composite field handling (base for split fields)SplitDateTimeField: Separate date and time inputs
Model-Related Fields:
ModelChoiceField: Foreign key selection with queryset supportModelMultipleChoiceField: Many-to-many selection
Model Integration
Implemented ✓
- Generated model forms (
ModelForm<T, P>): Descriptor-driven model validation and persistence- Explicit
#[model(form = true)]opt-in - Generated
{Model}FormSchemametadata and{Model}ModelFormData<P>typed payload ModelFormPolicy-controlled public field selection- Typed trusted setters for server-owned values
from_payloadfor explicit create intentfrom_payload_and_instancefor explicit update intent- Database-free, cached
build_instance()candidate construction - Caller-owned asynchronous
save(executor)persistence - Structured
ModelFormError, including retained database errors
- Explicit
Public JSON fields denied by the active policy are recorded during deserialization and rejected by native candidate construction. Hiding a field in HTML is not the security boundary. Server code may use the generated typed setter to supply an excluded editable value from a trusted source.
Formsets
Implemented ✓
-
FormSet: Managing multiple forms together
- Form collection management
- Validation across multiple forms
- Extra form generation
- Min/max form count constraints
- Deletion and ordering support
- Management form handling
- Non-form error tracking
-
ModelFormSet: Formset for model instances
- Generated payload and policy integration
- Candidate-based
min_numandmax_numvalidation - Asynchronous ordered persistence through a caller-owned executor
- Full candidate preflight before the first write
- Untouched create-mode extra forms are excluded from cardinality, preflight, and persistence
- Mutable extra-form access through
forms_mutfor submitted payloads - Persistence stops at the first error
- Inline formset support
- Configuration via
ModelFormSetConfig - Builder pattern API via
ModelFormSetBuilder
-
AdvancedModelFormSet: Cardinality-aware model formset
min_numandmax_numvalidation before candidate preflight- Incremental form insertion through
add_form - Asynchronous ordered persistence through a caller-owned executor
- Untouched create-mode extra forms are excluded from cardinality, preflight, and persistence; supplied or forbidden input marks an extra as submitted
- Inline parent persistence uses explicit
InlineFormSet::for_createorInlineFormSet::for_updateintent
Advanced Features
Implemented ✓
-
Form Wizard (
FormWizard): Multi-step form flow- Step definition and management (
WizardStep) - Conditional step availability
- Session data storage across steps
- Step navigation (next, previous, jump)
- Final data compilation
- Progress tracking
- Step definition and management (
-
form! Macro (with
macrosfeature): Declarative form definition- DSL for defining forms with fields, validators, and client validators
- Server-side and client-side validation rules
- Field property configuration
Validation
Implemented ✓
-
Field Validation: Individual field cleaning and validation
- Required field checking
- Type conversion and coercion
- Length constraints (CharField)
- Value range constraints (IntegerField, FloatField, DecimalField)
- Format validation (EmailField, URLField, DateField, etc.)
- Pattern matching (RegexField)
- Custom validators
-
Form Validation: Multi-field validation
- Custom clean methods (
add_clean_function) - Field-specific clean methods (
add_field_clean_function) - Cross-field validation
- Error aggregation
- Non-field errors
- Custom clean methods (
-
Error Handling: Comprehensive error reporting
FieldErrortypes (Required, Invalid, Validation)FormErrortypes (Field, Validation)- Custom error messages
- Error message internationalization support
Related Crates
Security and UI features have been moved to dedicated crates:
- CSRF Protection: Use
reinhardt-middleware::csrf - Rate Limiting: Use
reinhardt-middleware::rate_limit - Honeypot Fields: Use
reinhardt-middleware::honeypot - XSS Protection: Use
reinhardt-middleware::xss - HTML Rendering: Use
reinhardt-pagesfor form rendering
Usage Examples
Basic Form
use ;
use HashMap;
use json;
let mut form = new;
form.add_field;
form.add_field;
let mut data = new;
data.insert;
data.insert;
form.bind;
assert!;
Using the form! Macro
use form;
use HashMap;
use json;
let mut form = form! ;
let mut data = new;
data.insert;
data.insert;
form.bind;
assert!;
ModelForm
use ;
use ForeignKeyField;
use OrmExecutor;
use ;
use model;
use ;
;
async
Use from_payload_and_instance(payload, instance) for an update. Create and
update intent is selected by the constructor, not by a database existence
query or a primary-key guess.
build_instance() is the equivalent of Django's commit=False: it validates
and caches a model candidate without database access. Repeated calls and a
failed save() reuse that candidate, which makes persistence retryable.
Mutations made directly to the returned clone after build_instance() are the
caller's validation responsibility.
An excluded required value must have a declared model default, an automatic
model construction path, or a value supplied by a trusted typed setter before
construction. Otherwise build_instance() returns
ModelFormError::MissingModelField. Persistence failures remain
ModelFormError::Persistence, and database_error() returns the structured
DatabaseError.
Custom Validation
use ;
let mut form = new;
form.add_clean_function;
Architecture
- Field Layer: Individual field types with validation logic
- Form Layer: Form structure, binding, and validation
- Model Layer: ORM integration and automatic form generation
- Formset Layer: Multiple form management
- Wizard Layer: Multi-step form flows
- WASM Layer: Serializable metadata for client-side integration
Design Philosophy
This crate follows Django's forms philosophy:
- Declarative field definitions
- Separation of validation logic
- Model integration
- Extensible and customizable
- WASM-compatible core
License
Licensed under the BSD 3-Clause License.