Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Forms): extend validations in Field.NationalIdentityNumber #3888

Merged
merged 1 commit into from
Sep 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,35 @@ export const ValidationFunction = () => {
</ComponentBox>
)
}

export const ValidationExtendValidator = () => {
return (
<ComponentBox>
{() => {
const bornInApril = (value: string) =>
value.substring(2, 4) === '04'
? { status: 'valid' }
: { status: 'invalid' }

const myValidator = (value, { validators }) => {
const { dnrValidator, fnrValidator } = validators
const result = bornInApril(value)
if (result.status === 'invalid') {
return new Error('My error')
}

return [dnrValidator, fnrValidator]
}

return (
<Field.NationalIdentityNumber
required
value="53050129159"
validator={myValidator}
validateInitially
/>
)
}}
</ComponentBox>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,9 @@ Below is an example of the error message displayed when there's an invalid D num
You can provide your own validation function.

<Examples.ValidationFunction />

### Extend validation with custom validation function

You can [extend the existing validations](/uilib/extensions/forms/create-component/useFieldProps/info/#validators)(`dnrValidator` and `fnrValidator`) with your own validation function.

<Examples.ValidationExtendValidator />
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@ showTabs: true
import TranslationsTable from 'dnb-design-system-portal/src/shared/parts/TranslationsTable'
import PropertiesTable from 'dnb-design-system-portal/src/shared/parts/PropertiesTable'
import { fieldProperties } from '@dnb/eufemia/src/extensions/forms/Field/FieldDocs'
import { NationalIdentityNumberProperties } from '@dnb/eufemia/src/extensions/forms/Field/NationalIdentityNumber/NationalIdentityNumberDocs'

## Properties

### Field-specific props

| Property | Type | Description |
| ---------- | --------- | ------------------------------------------------------------------------------- |
| `validate` | `boolean` | _(optional)_ Using this prop you can disable the default validation. |
| `help` | `object` | _(optional)_ Provide a help button. Object consisting of `title` and `content`. |
<PropertiesTable props={NationalIdentityNumberProperties} />

### General props

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ function NationalIdentityNumber(props: Props) {
) {
return Error(errorFnr)
}
return undefined
},
[errorFnr]
)
Expand All @@ -66,7 +65,6 @@ function NationalIdentityNumber(props: Props) {
) {
return Error(errorDnr)
}
return undefined
},
[errorDnr]
)
Expand Down Expand Up @@ -94,6 +92,7 @@ function NationalIdentityNumber(props: Props) {
validator: validate
langz marked this conversation as resolved.
Show resolved Hide resolved
? props.validator || dnrAndFnrValidator
: undefined,
exportValidators: { dnrValidator, fnrValidator },
}

return <StringField {...StringFieldProps} />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { PropertiesTableProps } from '../../../../shared/types'

export const NationalIdentityNumberProperties: PropertiesTableProps = {
validate: {
doc: 'Using this prop you can disable the default validation.',
type: 'boolean',
status: 'optional',
},
help: {
doc: 'Provide a help button. Object consisting of `title` and `content`.',
type: 'object',
status: 'optional',
},
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react'
import { fireEvent, render, waitFor, screen } from '@testing-library/react'
import { Props } from '..'
import { Field, Form } from '../../..'
import { Field, Form, Validator } from '../../..'
import nbNO from '../../../constants/locales/nb-NO'

const nb = nbNO['nb-NO']
Expand Down Expand Up @@ -211,6 +211,38 @@ describe('Field.NationalIdentityNumber', () => {
})
})

it('should not validate extended validator when validate false', async () => {
const invalidFnr = '29040112345'

const bornInApril = (value: string) =>
value.substring(2, 4) === '04'
? { status: 'valid' }
: { status: 'invalid' }

const customValidator: Validator<string> = (value, { validators }) => {
const { dnrValidator, fnrValidator } = validators
const result = bornInApril(value)
if (result.status === 'invalid') {
return new Error('custom error')
}

return [dnrValidator, fnrValidator]
}

render(
<Field.NationalIdentityNumber
value={invalidFnr}
validateInitially
validate={false}
validator={customValidator}
/>
)
await expectNever(() => {
// Can't just waitFor and expect not to be in the document, it would approve the first render before the error might appear async.
expect(screen.queryByRole('alert')).toBeInTheDocument()
})
})

describe('should validate Norwegian D number', () => {
const validDNum = [
'53097248016',
Expand Down Expand Up @@ -304,4 +336,103 @@ describe('Field.NationalIdentityNumber', () => {
}
)
})

describe('should extend validation using custom validator', () => {
const validFnrNumApril = ['14046512368', '10042223293']
const validDNumApril = ['51041678171']

const validIds = [...validFnrNumApril, ...validDNumApril]

const invalidFnrNumApril = ['29040112345', '13047248032']
const invalidDNumApril = ['69040112345', '53047248032']

const validFnrNumNotApril = [
'58081633086',
'53050129159',
'65015439860',
]
const validDNumNotApril = ['08121312590', '12018503288', '03025742965']

const invalidIds = [...validFnrNumNotApril, ...validDNumNotApril]

const bornInApril = (value: string) =>
value.substring(2, 4) === '04'
? { status: 'valid' }
: { status: 'invalid' }

const customValidator: Validator<string> = (value, { validators }) => {
const { dnrValidator, fnrValidator } = validators
const result = bornInApril(value)
if (result.status === 'invalid') {
return new Error('custom error')
}

return [dnrValidator, fnrValidator]
}

it.each(validIds)('Valid identity number: %s', async (fnrNum) => {
render(
<Field.NationalIdentityNumber
validator={customValidator}
validateInitially
value={fnrNum}
/>
)
await expectNever(() => {
// Can't just waitFor and expect not to be in the document, it would approve the first render before the error might appear async.
expect(screen.queryByRole('alert')).toBeInTheDocument()
})
})

it.each(invalidIds)('Invalid identity number: %s', async (id) => {
render(
<Field.NationalIdentityNumber
validator={customValidator}
validateInitially
value={id}
/>
)
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
'custom error'
)
})
})

it.each(invalidDNumApril)('Invalid D number: %s', async (dNum) => {
render(
<Field.NationalIdentityNumber
validator={customValidator}
validateInitially
value={dNum}
/>
)
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorDnr
)
})
})

it.each(invalidFnrNumApril)(
'Invalid national identity number(fnr): %s',
async (fnr) => {
render(
<Field.NationalIdentityNumber
validator={customValidator}
validateInitially
value={fnr}
/>
)
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorFnr
)
})
}
)
})
})
Loading