From 7da262856b7481a94ebfb4b464db024e9138a203 Mon Sep 17 00:00:00 2001 From: Janry Date: Sat, 12 Mar 2022 23:32:36 +0800 Subject: [PATCH] fix(validator): fix unexpect validate with empty format (#2926) --- packages/validator/src/__tests__/validator.spec.ts | 13 +++++++++++++ packages/validator/src/rules.ts | 10 +++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/validator/src/__tests__/validator.spec.ts b/packages/validator/src/__tests__/validator.spec.ts index 65ec608fbed..27399d1b317 100644 --- a/packages/validator/src/__tests__/validator.spec.ts +++ b/packages/validator/src/__tests__/validator.spec.ts @@ -392,6 +392,19 @@ test('validate custom formats', async () => { noError(await validate('中文', 'custom')) }) +test('validate undefined format', async () => { + expect( + ( + await validate('a', { + required: false, + pattern: '(\\d{3,4}-\\d{7,8}-\\d{4})|(4\\d{4,9})|(\\d{3,4}-\\d{7,8})', + format: undefined, + message: 'error', + }) + ).error + ).toEqual(['error']) +}) + test('validator return boolean', async () => { hasError( await validate('123', { diff --git a/packages/validator/src/rules.ts b/packages/validator/src/rules.ts index 7475fc615c9..efc79545dd9 100644 --- a/packages/validator/src/rules.ts +++ b/packages/validator/src/rules.ts @@ -46,9 +46,13 @@ const extendSameRules = ( const RULES: IRegistryRules = { format(value, rule) { if (isValidateEmpty(value)) return '' - return !new RegExp(getValidateFormats(rule.format) || '').test(value) - ? rule.message - : '' + if (rule.format) { + const format = getValidateFormats(rule.format) + if (format) { + return !new RegExp(format).test(value) ? rule.message : '' + } + } + return '' }, required(value, rule) { if (rule.required === false) return ''