dnbexperience / eufemia

DNB Design System
https://eufemia.dnb.no
Other
50 stars 30 forks source link

Forms: Combined error messages are inflexible and presented in English #4052

Open kimroen opened 1 week ago

kimroen commented 1 week ago

🐛 Bug Report

When rendering a field with multiple validation props, a combined error message is shown. Example:

must NOT have more than 3 characters and must match pattern "^[a-zA-Z]$"

This error message has multiple problems:

Here's an example from our application:

CleanShot 2024-10-03 at 16 29 32@2x

To Reproduce

Here is a CodeSandbox demonstrating the issue

Expected behavior

The error message is displayed in Norwegian or English, depending on the set language. As a bonus, It would be nice to be able to customize (showing the pattern isn't great, for instance)

Eufemia Version

Browser JS: 10.51.1

Browser CSS: 10.51.1

kimroen commented 1 day ago

As one might expect, this is because when there's more than one error from ajv, we're just passing through the errors directly, concatenated with " and ".

This happens here:

https://github.com/dnbexperience/eufemia/blob/0d83b8171d99d60bd81b90aba136bd0130b37972/packages/dnb-eufemia/src/extensions/forms/hooks/useFieldProps.ts#L985-L988

This calls the function ajvErrorsToOneFormError:

https://github.com/dnbexperience/eufemia/blob/0d83b8171d99d60bd81b90aba136bd0130b37972/packages/dnb-eufemia/src/extensions/forms/utils/ajv.ts#L130-L148

Here, if there's just one error we transform it into a sensible FormError instance with extracted information, but if there are more then we fall back to some fairly simple behavior where we extract message and concat them all together:

https://github.com/dnbexperience/eufemia/blob/0d83b8171d99d60bd81b90aba136bd0130b37972/packages/dnb-eufemia/src/extensions/forms/utils/ajv.ts#L146-L147

I made this codesandbox where you can enter some text and see what the error objects look like (as well as replicating the concatenation behavior that leads to this error message):

Showing the error object output of validating the text from earlier examples

Now, I suppose the question is: What should it do instead?

Do we want it to combine multiple errors into one, or should we display multiple errors? Should we make ajv stop on the first error to avoid this all together (this matches the behavior of passing both a schema and validate function, for instance)?