diff --git a/src/NopeNumber.ts b/src/NopeNumber.ts index b9a56aa5..67b1ffdb 100644 --- a/src/NopeNumber.ts +++ b/src/NopeNumber.ts @@ -117,6 +117,18 @@ export class NopeNumber extends NopePrimitive { return this; } + public default(value: number) { + const rule: Rule = (entry) => { + if (this.isEmpty(entry)) { + return value; + } + + return entry as Awaited>; + }; + + return this.test(rule); + } + public validate(entry?: any, context?: Record): string | undefined { const value = !!entry ? Number(entry) : entry; diff --git a/src/NopeString.ts b/src/NopeString.ts index a90cee71..e2a44bc3 100644 --- a/src/NopeString.ts +++ b/src/NopeString.ts @@ -167,4 +167,16 @@ export class NopeString extends NopePrimitive { return this.test(rule); } + + public default(value: string) { + const rule: Rule = (entry) => { + if (this.isEmpty(entry)) { + return value; + } + + return entry as string; + }; + + return this.test(rule); + } } diff --git a/src/__tests__/NopeNumber.spec.ts b/src/__tests__/NopeNumber.spec.ts index 6ea47dca..8d94d1b5 100644 --- a/src/__tests__/NopeNumber.spec.ts +++ b/src/__tests__/NopeNumber.spec.ts @@ -236,4 +236,33 @@ describe('#NopeNumber', () => { await validateSyncAndAsync(Nope.number().integer('integerErrorMessage'), '12', undefined); }); }); + + describe('#default', () => { + it('should return a default value when entry is empty', async () => { + for (const { schema, value, expected } of [ + { + schema: Nope.number().default(5), + value: 0.1, + expected: 0.1, + }, + { + schema: Nope.number().default(10), + value: undefined, + expected: 10, + }, + { + schema: Nope.number().default(15), + value: null, + expected: 15, + }, + { + schema: Nope.number().default(101010), + value: 20, + expected: 20, + }, + ]) { + await validateSyncAndAsync(schema, value, expected); + } + }); + }); }); diff --git a/src/__tests__/NopeString.spec.ts b/src/__tests__/NopeString.spec.ts index fe80a6e4..d0833d5d 100644 --- a/src/__tests__/NopeString.spec.ts +++ b/src/__tests__/NopeString.spec.ts @@ -324,4 +324,35 @@ describe('#NopeString', () => { } }); }); + + describe('#default', () => { + it('should return a default value when entry is empty', async () => { + const ERR_MSG = 'error-message'; + + for (const { schema, value, expected } of [ + { + schema: Nope.string().default('default-value').email(ERR_MSG), + value: '', + expected: 'default-value', + }, + { + schema: Nope.string().default('default-value-trim').trim().email(ERR_MSG), + value: ' ', + expected: 'default-value-trim', + }, + { + schema: Nope.string().default('_ftonato ').email(ERR_MSG), + value: undefined, + expected: '_ftonato ', + }, + { + schema: Nope.string().trim().default('will-not-assume-this-value').email(ERR_MSG), + value: ' aaa ', + expected: 'aaa', + }, + ]) { + await validateSyncAndAsync(schema, value, expected); + } + }); + }); });