From 10768ff195b492a029c96cfb0e903db7fe2b12dd Mon Sep 17 00:00:00 2001 From: Andrew Shubnikov <32542672+shbov@users.noreply.github.com> Date: Tue, 20 Aug 2024 16:23:10 +0300 Subject: [PATCH] feat: add ability to use custom patternError (#224) --- src/lib/kit/utils/__tests__/common.test.ts | 30 ++++++++++++++++++++++ src/lib/kit/utils/common.ts | 14 ++++++++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/lib/kit/utils/__tests__/common.test.ts b/src/lib/kit/utils/__tests__/common.test.ts index d6fcc41c..773ced3d 100644 --- a/src/lib/kit/utils/__tests__/common.test.ts +++ b/src/lib/kit/utils/__tests__/common.test.ts @@ -131,6 +131,36 @@ describe('kit/utils/common', () => { expect(prepareSpec({properties: {prop: {type: 'NUMBER'}}} as any)).toMatchObject({ properties: {prop: {type: 'number'}}, }); + + const getErrorMessage = (regexp?: string) => { + return `My custom error message for ${regexp}`; + }; + + expect(prepareSpec({pattern: '[a-zA-Z0-9]'} as any, false, getErrorMessage)).toMatchObject({ + pattern: '[a-zA-Z0-9]', + patternError: 'My custom error message for [a-zA-Z0-9]', + }); + + expect( + prepareSpec( + { + properties: { + test: { + pattern: '[a-zA-Z0-9]', + }, + }, + } as any, + false, + getErrorMessage, + ), + ).toMatchObject({ + properties: { + test: { + pattern: '[a-zA-Z0-9]', + patternError: 'My custom error message for [a-zA-Z0-9]', + }, + }, + }); }); test('isCorrectSizeParams', () => { diff --git a/src/lib/kit/utils/common.ts b/src/lib/kit/utils/common.ts index 6e26b62a..3a09b84c 100644 --- a/src/lib/kit/utils/common.ts +++ b/src/lib/kit/utils/common.ts @@ -4,6 +4,7 @@ import isNil from 'lodash/isNil'; import isObject from 'lodash/isObject'; import isObjectLike from 'lodash/isObjectLike'; import isString from 'lodash/isString'; +import isEmpty from 'lodash/isEmpty'; import { FormValue, @@ -63,6 +64,7 @@ export const isNotEmptyValue = (value: FormValue | undefined, spec: Spec | undef export const prepareSpec = ( spec: Type, parseJsonDefaultValue?: boolean, + overridePatternError?: (pattern?: string) => string, ): Type => { if (isObjectLike(spec)) { const result: Record = cloneDeep(spec); @@ -140,8 +142,12 @@ export const prepareSpec = ( } } + if (!isEmpty(result.pattern) && isEmpty(result.patternError) && overridePatternError) { + result.patternError = overridePatternError(result.pattern); + } + if (result.items) { - result.items = prepareSpec(result.items, parseJsonDefaultValue); + result.items = prepareSpec(result.items, parseJsonDefaultValue, overridePatternError); } if (result.maximum === 0 && result.minimum === 0) { @@ -163,7 +169,11 @@ export const prepareSpec = ( if (isObjectLike(result.properties)) { Object.keys(result.properties).forEach((key) => { - result.properties[key] = prepareSpec(result.properties[key], parseJsonDefaultValue); + result.properties[key] = prepareSpec( + result.properties[key], + parseJsonDefaultValue, + overridePatternError, + ); }); }