Skip to content

Commit

Permalink
Fix for error message value injection
Browse files Browse the repository at this point in the history
  • Loading branch information
henit committed Nov 13, 2023
1 parent b348a59 commit 5f17902
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,38 @@ describe('Field.String', () => {
})
})
})

describe('errorMessages', () => {
it('should show provided errorMessages based on validation rule', () => {
render(
<Field.String
emptyValue=""
value=""
errorMessages={{
required: 'You need this',
}}
required
validateInitially
/>
)
expect(screen.getByText('You need this')).toBeInTheDocument()
})

it('should show provided errorMessages based on validation rule with injected value', () => {
render(
<Field.String
emptyValue=""
value=""
errorMessages={{
minLength: 'At least {minLength}..',
}}
minLength={4}
validateInitially
/>
)
expect(screen.getByText('At least 4..')).toBeInTheDocument()
})
})
})

describe('with data context', () => {
Expand Down
26 changes: 18 additions & 8 deletions packages/dnb-eufemia/src/extensions/forms/hooks/useDataValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,18 +170,28 @@ export default function useDataValue<
* Prepare error from validation logic with correct error messages based on props
*/
const prepareError = useCallback(
(error: Error | FormError | undefined): FormError => {
(error: Error | FormError | undefined): FormError | undefined => {
if (error === undefined) {
return
}
const withCorrectMessage =

if (
error instanceof FormError &&
typeof error.validationRule === 'string' &&
errorMessagesRef?.[error.validationRule] !== undefined
? new FormError(errorMessagesRef[error.validationRule])
: error
return withCorrectMessage
errorMessagesRef.current?.[error.validationRule] !== undefined
) {
const message = errorMessagesRef.current[
error.validationRule
].replace(
`{${error.validationRule}}`,
props?.[error.validationRule]
)
return new FormError(message)
}

return error
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)

Expand Down Expand Up @@ -290,8 +300,8 @@ export default function useDataValue<

const dataContextError = path ? dataContextErrors?.[path] : undefined
useEffect(() => {
contextErrorRef.current = dataContextError
}, [dataContextError])
contextErrorRef.current = prepareError(dataContextError)
}, [dataContextError, prepareError])

useEffect(() => {
if (dataContext.showAllErrors) {
Expand Down

0 comments on commit 5f17902

Please sign in to comment.