From accb3c69600a979420e662bb37eb37c1bcc26e8c Mon Sep 17 00:00:00 2001 From: harrygr Date: Sun, 26 Aug 2018 12:14:01 +0100 Subject: [PATCH] feat: Exclude valid fields in validation result --- src/index.spec.ts | 18 +++++++++++++++++- src/index.ts | 7 +++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/index.spec.ts b/src/index.spec.ts index 212e049..c857216 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -21,7 +21,7 @@ describe('Basic validator usage', () => { ).toEqual({}) }) - it('only returns a message for the first failing contrait for a field', () => { + it('only returns a message for the first failing constraint for a field', () => { const ageValidator = makeValidator({ age: [required, atLeast18] }) expect( @@ -51,4 +51,20 @@ describe('Basic validator usage', () => { expect(result).toEqual({ password: 'Should be equal' }) }) + + it('does not include the keys of passing fields in the validation result', () => { + const personValidator = makeValidator({ + name: [required], + age: [required], + }) + + const fields = { + name: 'Tim', + age: undefined, + } + + const result = personValidator(fields) + + expect(result).not.toHaveProperty('name') + }) }) diff --git a/src/index.ts b/src/index.ts index f2b757a..c2eb4d3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,9 +5,8 @@ export type Constraint = ( export type Constraints = Partial< Record[]> > -export type ValidationResult = Record< - keyof F, - string | undefined +export type ValidationResult = Partial< + Record > export function makeValidator(constraints: Constraints) { @@ -29,7 +28,7 @@ export function makeValidator(constraints: Constraints) { undefined, ) - return Object.assign({}, acc, { [fieldName]: error }) + return error ? Object.assign({}, acc, { [fieldName]: error }) : acc } return fieldNames.reduce(getErrors, {} as ValidationResult)