Design: type-safe Filterable trait for concrete struct validation#91
Draft
Design: type-safe Filterable trait for concrete struct validation#91
Conversation
…cro spec, and code sketches Co-authored-by: elycruz <603428+elycruz@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] Investigate type-safe FieldFilter and Form for struct validation
Design: type-safe Filterable trait for concrete struct validation
Feb 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
FieldFilterandFormare hardwired toHashMap<String, Value>— field names are runtime strings, values are dynamically typed, and rule/type mismatches are only caught at runtime. This PR adds a design document proposing a trait-based path that restores compile-time guarantees for known structs.Design document:
md/plans/filterable_trait_design.mdFilterabletrait inwalrs_inputfilter—validate(&self),filter(self),process(self)with provided default#[derive(Filterable)]proc-macro — newwalrs_inputfilter_derivecrate behind aderivefeature gate#[validate(required, min_length = 3, email, ...)]and#[filter(trim, lowercase, ...)]mapped to existingRule<T>/Filter<T>enums#[cross_validate(fn_name)]#[validate(nested)]recursively validatesFilterablefields, prefixes violation keys with dot-notationfilter(self) -> SelfavoidsDefault/ClonerequirementsFormbridge — opt-inInto<FormData>/TryFrom<FormData>generation via#[filterable(into_form_data)]HashMap<String, Value>/FormDatapath unchangedOpen question decisions
#[validate(nested)]FieldFiltergeneric extensionFilterablereplaces it for typed use cases;FieldFilterstays as dynamic pathInto<FormData>/TryFrom<FormData>walrs_inputfilter_deriveExample target API
Generated code constructs
Rule::<String>::Required.and(Rule::MinLength(3))— aRule::<i64>::Minon aStringfield would be a compile error, not a runtimeTypeMismatch.Original prompt
This section details on the original issue you should resolve
<issue_title>Investigate type-safe FieldFilter and Form for concrete struct validation</issue_title>
<issue_description>## Summary
FieldFilterandFormare currently hardwired toHashMap<String, Value>/FormDatafor hydration and validation. Field names are runtime strings, values are the dynamically-typedValueenum, and type correctness is deferred entirely to runtimeTypeMismatchviolations. In a statically-typed language like Rust, users should get compiler errors when wiring incompatible rules to fields — not runtime failures.This issue proposes investigating a trait-based design that lets users validate concrete structs directly, restoring compile-time guarantees while preserving the existing
HashMap<String, Value>path for dynamic/config-driven and WASM use cases.Problem
Current
FieldFilter(hardwired toHashMap<String, Value>)FieldFilter::validate(field_filter.rs) accepts&HashMap<String, Value>:Valueenum — aRule::<Value>::MinLengthapplied to aValue::I64produces a runtimeTypeMismatchviolation instead of a compile error.Current
Form(hardwired toFormData)Form::validate(form.rs) delegates toFieldFilteror per-element validation, both operating onFormData(aHashMap<String, Value>newtype):The same runtime-only type safety issues apply.
What users expect in Rust
Users should be able to write:
…attach validation rules per field with compile-time type checking, and call a single
validate(&user_address)method — with the compiler rejecting rule/type mismatches (e.g.,Rule::<i64>::Minon aStringfield).Proposed Direction
1.
FilterabletraitIntroduce a trait in
walrs_inputfilterthat concrete structs implement:validate(&self)— validates every field viaRule<T>::validate_ref()/Rule<T>::validate()with the correct concreteTper field, then runs cross-field rules. Collects errors intoFormViolationskeyed by field name.filter(self)— takes ownership, applies per-fieldFilter<T>::apply(), returnsSelf. Ownership avoidsmem::takehacks on non-Defaultfields.process(self)— provided default: filter then validate.Both manual trait implementation and derive-macro-generated implementations must be supported.
2. Derive macro (
#[derive(Filterable)])A proc-macro crate (
walrs_inputfilter_derive) provides#[derive(Filterable)]with field-level attribute annotations:Generated code:
validate(&self)constructsRule::Required.and(Rule::MinLength(3))forstreet, callsrule.validate_ref(self.street.as_str()), collects violations keyed by"street".filter(self)constructsFilter::<String>::Trim, applies it toself.street, returnsSelf { street: filtered, ..self }.#[validate(...)]attributes combine viaRule::and().#[filter(...)]attributes produce aFilter::Chain(...).Supported annotations:
|
#[validate(...)]| Maps to ||---|---|
|
required|Rule::Required||
min_length = N|Rule::MinLength(N)||
max_length = N|Rule::MaxLength(N)||
email|Rule::Email||
url|Rule::Url||
pattern = "regex"|Rule::Pattern("regex".into())||
min = N|Rule::Min(N)||
max = N|Rule::Max(N)||
custom = "path::to::fn"|Rule::Custom(Arc::new(path::to::fn))||
#[filter(...)]| Maps to ||---|---|
|
trim|Filter::Trim||
lowercase|Filter::Lowercase||
uppercase|Filter::Uppercase||
strip_tags|Filter::StripTags||
slug|Filter::Slug { max_length: None }||
custom = "path::to::fn"|Filter::Custom(Arc::new(path::to::fn))|A **builder/config-bl...
💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.