-
Notifications
You must be signed in to change notification settings - Fork 28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Is there an idiomatic way to validate the contents (keys & values) of a map? #82
Comments
Validating keys is not possible right now without custom validators, and the only way you can validate the values in a One possible improvement here would be to add a modifier similar to struct Foo {
#[garde(
key(length(min = 3)), // applied to `K`
inner(length(min = 10)), // applied to `V`
)]
bar: HashMap<K, V>,
} The error message would probably look like:
As for validating a One thing I've seen done by serde is to implement a way to "adapt" one type to be validated as if it was another. Once again, here's a very rough idea: mod dashmap_adapter {
// the `adapt` modifier will cause the proc macro to bypass the usual trait-based validation
// logic, and instead rely on functions present in this module:
// re-export all the garde rules
// because of the glob import, anything defined in this module will take precedence
pub use garde::rules::*;
// for example, here's how you'd adapt the `inner` modifier to work on `DashMap`:
pub mod inner {
pub fn apply<K, V, F>(map: &DashMap<K, V>, f: F)
where
K: PathComponentKind,
F: FnMut(&V, &K),
{
for (key, value) in map.iter() {
f(value, key)
}
}
}
}
struct Foo {
#[garde(
inner(length(min = 10)),
adapt(dashmap_adapter), // use the `dashmap_adapter` module
)]
bar: DashMap<K, V>,
} Now instead of calling |
Thank you for your in-depth response. I'll dig into it and hopefully have something I can share back to garde to help others when I'm done. |
I appreciate garde. It has made validating structures not just easier, but a natural part of my development. However, I've run into a situation where I need to validate a HashMap (actually a DashMap) that is a member of a struct. If I try to validate it directly, it fails because there is no Display implementation for DashMap. I suspect I may be able to write a custom validator function...maybe? Or..I could wrap the DashMap in a newtype and implement Validate on that type manually...maybe? But, is there an existing best way to validate the keys and values of a map? I would love to be able to use the validation rules built into garde on the keys and values in the map and if I write custom validation code, I lose all of that.
Thanks in advance.
The text was updated successfully, but these errors were encountered: