dnbexperience / eufemia

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

feat(Forms): add `preventChangeValidator` to each field #3933

Closed tujoworker closed 2 days ago

tujoworker commented 5 days ago

Should we even call it "Validator"? It acts very similar and has the same API. But it does also a little more, as it actually prevents the "new value" to be a part of the data set. Something which is not possible with our other validators. But on the other side, it also shows an error. So it "validates" the field. Any thoughts?

Quick example:

<Field.SelectCountry
  label="Land du er statsborger i"
  required
  preventChangeValidator={(value, { connectWithPath }) => {
    const { getValue } = connectWithPath('/countries')
    if ((getValue() || []).includes(value)) {
      return new Error(
        'You can not have the same country twice',
      )
    }
  }}
/>
vercel[bot] commented 5 days ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
eufemia ✅ Ready (Inspect) Visit Preview 💬 Add feedback Sep 15, 2024 5:29am
codesandbox-ci[bot] commented 5 days ago

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

langz commented 3 days ago

I think we should think about this PR:

Could/should this be a prop to Iterate.Array, like allowDuplicates or uniqueValue.

Here are two scenarios I quickly came across when testing the newly updated example:

Not being able to submit after removing the duplicate item:

https://github.com/user-attachments/assets/828d80fb-9211-4a19-988a-15b769aa382c

Not being able to submit after changing the duplicate item to be an other country(unique):

https://github.com/user-attachments/assets/46357831-1f5c-42ef-be77-a3dc1cdece89

tujoworker commented 2 days ago

Thank you for the feedback 🫶

I agree, we should not add this validator, because it creates a couple of UX issues you demonstrate, but rather use the validator we have on the Iterate.Array.

This PR #3953 adds a duplication check.