Skip to content
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
28 changes: 28 additions & 0 deletions src/features/formData/convertData.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { JSONSchema7 } from 'json-schema';

import { convertData } from 'src/features/formData/convertData';

describe('convertData with format date-time', () => {
const schema: JSONSchema7 = { type: 'string', format: 'date-time' };

it.each(['2026-01-01', '2026-01-01T12:34:56.123+01:00'])('accepts %s', (value) => {
expect(convertData(value, schema)).toEqual({ newValue: value, error: false });
});

it.each(['32.13.2026', '2026-13-32', '12.34.____'])('rejects %s', (value) => {
expect(convertData(value, schema)).toEqual({ newValue: undefined, error: true });
});

it('validates date-time in an anyOf sub-schema', () => {
const nullableSchema: JSONSchema7 = { anyOf: [schema, { type: 'null' }] };
expect(convertData('2026-01-01', nullableSchema)).toEqual({ newValue: '2026-01-01', error: false });
expect(convertData('32.13.2026', nullableSchema)).toEqual({ newValue: undefined, error: true });
});

it('does not reject an invalid date for format "date", as the C# string accepts any text (validation still flags it)', () => {
expect(convertData('32.13.2026', { type: 'string', format: 'date' })).toEqual({
newValue: '32.13.2026',
error: false,
});
});
});
9 changes: 7 additions & 2 deletions src/features/formData/convertData.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { JSONSchema7, JSONSchema7Definition } from 'json-schema';

import { strictParseISO } from 'src/app-components/Datepicker/utils/dateHelpers';

interface ReturnType {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
newValue: any;
Expand Down Expand Up @@ -55,15 +57,18 @@ function convertToType(value: Value, schema: JSONSchema7 | JSONSchema7Definition
// eslint-disable-next-line @typescript-eslint/no-explicit-any
AllValidTypes.includes(schema.type as any)
) {
return convertToScalar(value, schema.type as ValidTypes, schema['@xsdType']);
return convertToScalar(value, schema.type as ValidTypes, schema['@xsdType'], schema.format);
}

throw new Error(`Unsupported schema: ${JSON.stringify(schema)}`);
}

function convertToScalar(value: Value, targetType: ValidTypes, xsdType?: string): ReturnType {
function convertToScalar(value: Value, targetType: ValidTypes, xsdType?: string, format?: string): ReturnType {
const sVal = String(value);
if (targetType === 'string') {
if (format === 'date-time' && !strictParseISO(sVal)) {
return { newValue: undefined, error: true };
}
return { newValue: sVal, error: false };
}

Expand Down
19 changes: 19 additions & 0 deletions src/layout/Datepicker/DatepickerComponent.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,25 @@ describe('DatepickerComponent', () => {
});
});

it('should show its own validation message and not save when an invalid date is typed into a date-time field', async () => {
const { mutations } = await render({
component: { showValidations: ['AllExceptRequired'] },
queries: {
fetchDataModelSchema: async () => ({
type: 'object',
properties: { myDate: { type: 'string', format: 'date-time' } },
}),
},
});

await userEvent.type(screen.getByRole('textbox'), '32.13.2026');
await userEvent.tab();

expect(await screen.findByText('Ugyldig datoformat. Bruk formatet DD.MM.YYYY.')).toBeInTheDocument();
expect(screen.queryByText('Feil format eller verdi')).not.toBeInTheDocument();
expect(mutations.doPatchFormData.mock).not.toHaveBeenCalled();
});

it('should not have aria-describedby if textResources.description does not exist', async () => {
await render({ component: { textResourceBindings: {}, id: 'test-id' } });
const inputField = screen.getByRole('textbox');
Expand Down
12 changes: 11 additions & 1 deletion src/layout/Datepicker/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ export class Datepicker extends DatepickerDef implements ValidateComponent, Vali
);
}

/**
* Avoid duplicate validation message.
*/
private static invalidDataFormatFilter(validation: BaseValidation): boolean {
return !(
validation.source === FrontendValidationSource.InvalidData &&
validation.message.key === 'validation_errors.pattern'
);
}

/**
* Avoid duplicate validation message.
*/
Expand All @@ -97,7 +107,7 @@ export class Datepicker extends DatepickerDef implements ValidateComponent, Vali
}

getValidationFilters(baseComponentId: string, layoutLookups: LayoutLookups): ValidationFilterFunction[] {
const filters = [Datepicker.schemaFormatFilter];
const filters = [Datepicker.schemaFormatFilter, Datepicker.invalidDataFormatFilter];
const component = layoutLookups.getComponent(baseComponentId, 'Datepicker');

if (component.minDate) {
Expand Down
4 changes: 3 additions & 1 deletion src/layout/Datepicker/useDatepickerValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ export function useDatepickerValidation(baseComponentId: string): ComponentValid
const currentLanguage = useCurrentLanguage();
const field = useDataModelBindingsFor(baseComponentId, 'Datepicker')?.simpleBinding;
const component = useItemWhenType(baseComponentId, 'Datepicker');
const data = FD.useDebouncedPick(field);
const validData = FD.useDebouncedPick(field);
const invalidData = FD.useInvalidDebouncedPick(field);
const data = validData ?? invalidData;
const minDate = getDateConstraint(component?.minDate, 'min');
const maxDate = getDateConstraint(component?.maxDate, 'max');
const format = getDateFormat(component?.format, currentLanguage);
Expand Down
Loading