jprochazk / garde

A powerful validation library for Rust
Apache License 2.0
476 stars 28 forks source link

Support custom error codes #105

Open jprochazk opened 7 months ago

jprochazk commented 7 months ago

Two parts:

  1. Add a code: Option<Cow<'static, str>> field to garde::Error

  2. Add a way to set the code for a specific rule via the proc macro.

The unresolved question here is syntax:

Option A:

#[garde(length(min = 1, code = "custom_error_code"))]

Option B:

#[garde(code("custom_error_code", length(min = 1)))]

(A) would require some hacks to "intercept" the code value during parsing. Both would work by intercepting the error returned by a rule and set its code field in the proc macro output. (B) seems easier to implement, but those coming from validator likely expect (A).

lasantosr commented 7 months ago

I think either (A) or (B) are good to go, as long as different rules can set different codes, it doesn't matter that much the syntax that's more similar to validator.

It must support both with and without code tho, so maybe the (A) its easier to understand in those cases.

btw, https://github.com/TedDriggs/darling might help with attribute parsing

boyswan commented 4 months ago

Based on: #[garde(length(min = 1, code = "custom_error_code"))]

Would there be a way to also dynamically capture the criteria? The code is helpful, but in the real world it you really need to know what min is. However I imagine it would be tricky to know how or where to add this to the error struct.

I'm spitballing, but perhaps something along the lines of criteria: HashMap<(String, String), Value> which would equate to HashMap<("length", "min"), Value::Number(1)>>. I'm sure there's plenty reasons why this is wrong/won't work - but hopefully you get the idea!

Custom codes/messages is the one feature that is preventing be being able to migrate my validation to garde - I'd be really happy to see this!

jprochazk commented 4 months ago

There's an issue open for serializing constraints, which are rules + their inputs: