garde icon indicating copy to clipboard operation
garde copied to clipboard

Support custom error codes

Open jprochazk opened this issue 1 year ago • 4 comments

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).

jprochazk avatar Mar 29 '24 23:03 jprochazk

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

lasantosr avatar Mar 30 '24 07:03 lasantosr

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!

boyswan avatar Jul 03 '24 16:07 boyswan

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

  • https://github.com/jprochazk/garde/issues/3

jprochazk avatar Jul 03 '24 17:07 jprochazk

To me the PR looks feasible. Any updates on this? Thanks @jprochazk

mknet avatar Mar 07 '25 17:03 mknet