Skip to content

Commit

Permalink
Add createAboveAgeValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
tujoworker committed Oct 10, 2024
1 parent 8641d33 commit a7f05f8
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 63 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import ComponentBox from '../../../../../../shared/tags/ComponentBox'
import { createAboveAgeValidator } from '@dnb/eufemia/src/extensions/forms/Field/NationalIdentityNumber'
import { Field } from '@dnb/eufemia/src/extensions/forms'

export const Empty = () => {
Expand Down Expand Up @@ -191,10 +192,11 @@ export const ValidationExtendValidator = () => {

export const ValidationExtendValidatorAdult = () => {
return (
<ComponentBox>
<ComponentBox scope={{ createAboveAgeValidator }}>
{() => {
const adultValidator = createAboveAgeValidator(18)
const myAdultValidator = (value, { validators }) => {
const { adultValidator, dnrAndFnrValidator } = validators
const { dnrAndFnrValidator } = validators

return [dnrAndFnrValidator, adultValidator]
}
Expand All @@ -214,10 +216,11 @@ export const ValidationExtendValidatorAdult = () => {

export const ValidationFnrAdult = () => {
return (
<ComponentBox>
<ComponentBox scope={{ createAboveAgeValidator }}>
{() => {
const adultValidator = createAboveAgeValidator(18)
const myFnrAdultValidator = (value, { validators }) => {
const { adultValidator, fnrValidator } = validators
const { fnrValidator } = validators

return [fnrValidator, adultValidator]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ import { NationalIdentityNumberProperties } from '@dnb/eufemia/src/extensions/fo
- validates the identification number as a national identity number (fødselsnummer) when first digit is 3 or less.
- `adultValidator`: validates if the identification number has a date of birth that is 18 years or older. It uses only the 9 first digits of an identification number to validate, first 6 digits representing the birth of date, and the next three digits are individual numbers. It does not validate the identification number, therefore it's quite common to use this validator together with one of the validators above (`dnrValidator`, `fnrValidator` or `dnrAndFnrValidator`) to validate the identification number as well.

You can create your own `adultValidator` by using the `createAboveAgeValidator` function. It takes an age as a parameter and returns a validator function. The validator function takes a value and returns an error message if the value is not above the given age.

You need to import the `createAboveAgeValidator` function from the `Field.NationalIdentityNumber` component:

```tsx
import { createAboveAgeValidator } from '@dnb/eufemia/extensions/forms/Field/NationalIdentityNumber'

// Create a validator that validates if the value is above 18 years old
const above18Validator = createAboveAgeValidator(18)
```

See the following [example](/uilib/extensions/forms/feature-fields/NationalIdentityNumber/#extend-validation-with-custom-validation-function) on how to extend validation using the exposed validators.

## Translations
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useCallback, useMemo } from 'react'
import StringField, { Props as StringFieldProps } from '../String'
import { dnr, fnr } from '@navikt/fnrvalidator'
import { Validator } from '../../types'
import { FormError, Validator } from '../../types'

import useErrorMessage from '../../hooks/useErrorMessage'
import useTranslation from '../../hooks/useTranslation'
Expand All @@ -14,14 +14,14 @@ export type Props = Omit<StringFieldProps, 'onBlurValidator'> & {

function NationalIdentityNumber(props: Props) {
const translations = useTranslation().NationalIdentityNumber
const { label, errorRequired, errorFnr, errorDnr, errorAdult } =
const { label, errorRequired, errorFnr, errorDnr, errorBelowAge } =
translations
const errorMessages = useErrorMessage(props.path, props.errorMessages, {
required: errorRequired,
pattern: errorFnr,
errorFnr,
errorDnr,
errorAdult,
errorBelowAge,
})

const fnrValidator = useCallback(
Expand Down Expand Up @@ -62,18 +62,6 @@ function NationalIdentityNumber(props: Props) {
[dnrValidator, fnrValidator]
)

const adultValidator = useCallback(
(value: string) => {
// if (value !== undefined && value.length < 9) {
// return Error(errorAdultPattern)
// }
if (value !== undefined && !is18YearsOrOlder(value)) {
return Error(errorAdult)
}
},
[errorAdult]
)

const {
validate = true,
omitMask,
Expand Down Expand Up @@ -120,33 +108,34 @@ function NationalIdentityNumber(props: Props) {
dnrValidator,
fnrValidator,
dnrAndFnrValidator,
adultValidator,
},
}

return <StringField {...StringFieldProps} />
}

function is18YearsOrOlder(value: string) {
if (!new RegExp('^[0-9]{11}$').test(value)) return false
export function getAgeByBirthDate(birthDate: Date): number {
const today = new Date()
const age = today.getFullYear() - birthDate.getFullYear()
const month = today.getMonth() - birthDate.getMonth()
const day = today.getDate() - birthDate.getDate()

function getAge(birthDate: Date): number {
const today = new Date()
const age = today.getFullYear() - birthDate.getFullYear()
const month = today.getMonth() - birthDate.getMonth()
const day = today.getDate() - birthDate.getDate()
if (month < 0 || (month === 0 && day < 0)) {
return age - 1
}

if (month < 0 || (month === 0 && day < 0)) {
return age - 1
}
return age
}

return age
export function getBirthDateByFnrOrDnr(value: string) {
if (value === undefined) {
return // stop here
}

const yearPart = value.substring(4, 6)
const individNumber = Number.parseInt(value.substring(6, 9))
const individualNumber = Number.parseInt(value.substring(6, 9))

const isBornIn20XX = individNumber >= 500 && individNumber <= 999
const isBornIn20XX = individualNumber >= 500 && individualNumber <= 999
const year = isBornIn20XX ? `20${yearPart}` : `19${yearPart}`
const month = Number.parseInt(value.substring(2, 4))

Expand All @@ -157,9 +146,24 @@ function is18YearsOrOlder(value: string) {
const day = isDnr
? Number.parseInt(value.substring(0, 2)) - 40
: Number.parseInt(value.substring(0, 2))
const date = new Date(Number.parseInt(year), month - 1, day)

return getAge(date) >= 18
return new Date(Number.parseInt(year), month - 1, day)
}

export function createAboveAgeValidator(age: number) {
return (value: string) => {
if (typeof value !== 'string' || value.length < 9) {
return
}

const date = getBirthDateByFnrOrDnr(value)
if (getAgeByBirthDate(date) < age) {
return new FormError('NationalIdentityNumber.errorBelowAge', {
validationRule: 'errorBelowAge', // "validationRule" Will be removed in future PR
messageValues: { age: String(age) },
})
}
}
}

NationalIdentityNumber._supportsSpacingProps = true
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import React from 'react'
import { render, waitFor, screen } from '@testing-library/react'
import { Field, Validator } from '../../..'
import { createAboveAgeValidator } from '../NationalIdentityNumber'

import nbNO from '../../../constants/locales/nb-NO'

const nb = nbNO['nb-NO']

describe('Field.NationalIdentityNumber with adultValidator', () => {
const errorBelowAge = nb.NationalIdentityNumber.errorBelowAge.replace(
'{age}',
'18'
)
const adultValidator = createAboveAgeValidator(18)
const extendingDnrAndFnrValidatorWithAdultValidator: Validator<
string
> = (value, { validators }) => {
const { adultValidator, dnrAndFnrValidator } = validators
const { dnrAndFnrValidator } = validators

return [dnrAndFnrValidator, adultValidator]
}
Expand All @@ -19,7 +25,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
value,
{ validators }
) => {
const { adultValidator, dnrValidator } = validators
const { dnrValidator } = validators

return [dnrValidator, adultValidator]
}
Expand All @@ -28,14 +34,12 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
value,
{ validators }
) => {
const { adultValidator, fnrValidator } = validators
const { fnrValidator } = validators

return [fnrValidator, adultValidator]
}

const myAdultValidator: Validator<string> = (value, { validators }) => {
const { adultValidator } = validators

const myAdultValidator: Validator<string> = () => {
return [adultValidator]
}

Expand All @@ -56,20 +60,18 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
})
})

it('should display error when validateInitially and value', async () => {
it.skip('should display error when value is invalid', async () => {
render(
<Field.NationalIdentityNumber
onBlurValidator={myAdultValidator}
validateInitially
value="123"
value="123" // outputs the age of 105 years, which is valid
/>
)

await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
)
expect(screen.queryByRole('alert')).toHaveTextContent(errorBelowAge)
})
})

Expand Down Expand Up @@ -213,7 +215,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
errorBelowAge
)
})
}
Expand Down Expand Up @@ -251,7 +253,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
errorBelowAge
)
})
}
Expand Down Expand Up @@ -291,7 +293,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
errorBelowAge
)
})
}
Expand Down Expand Up @@ -373,7 +375,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
errorBelowAge
)
})
}
Expand Down Expand Up @@ -455,7 +457,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
errorBelowAge
)
})
}
Expand Down Expand Up @@ -513,7 +515,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
errorBelowAge
)
})
}
Expand Down Expand Up @@ -574,7 +576,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
errorBelowAge
)
})
}
Expand Down Expand Up @@ -632,7 +634,7 @@ describe('Field.NationalIdentityNumber with adultValidator', () => {
await waitFor(() => {
expect(screen.queryByRole('alert')).toBeInTheDocument()
expect(screen.queryByRole('alert')).toHaveTextContent(
nb.NationalIdentityNumber.errorAdult
errorBelowAge
)
})
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react'
import { Field, Validator } from '../../..'
import { Wrapper } from 'storybook-utils/helpers'
import { createAboveAgeValidator } from '../NationalIdentityNumber'

export default {
title: 'Eufemia/Extensions/Forms/NationalIdentityNumber',
Expand All @@ -10,21 +11,17 @@ const simpleValidator = (value) => {
return value?.length < 4 ? Error('At least 4 characters') : undefined
}

// const alwaysErrorValidator = (value) => {
// return Error('Always Error Validator')
// }

const myAdultValidator: Validator<string> = (value, { validators }) => {
const { adultValidator } = validators
const adultValidator = createAboveAgeValidator(18)

const myAdultValidator: Validator<string> = () => {
return [adultValidator]
}

const myAdultFnrDnrValidator: Validator<string> = (
value,
{ validators }
) => {
const { adultValidator, dnrAndFnrValidator } = validators
const { dnrAndFnrValidator } = validators

return [dnrAndFnrValidator, adultValidator]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export default {
errorRequired: 'You must enter a national identity number.',
errorFnr: 'Invalid national identity number.',
errorDnr: 'Invalid D number.',
errorAdult: 'Must be atleast 18 years of age.',
errorBelowAge: 'Must be at least {age} years of age.',
},
OrganizationNumber: {
label: 'Organisation number',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export default {
errorRequired: 'Du må fylle inn et fødselsnummer.',
errorFnr: 'Ugyldig fødselsnummer.',
errorDnr: 'Ugyldig d-nummer.',
errorAdult: 'Må være minst 18 år.',
errorBelowAge: 'Må være minst {age} år.',
},
OrganizationNumber: {
label: 'Organisasjonsnummer',
Expand Down

0 comments on commit a7f05f8

Please sign in to comment.